Calculate relative time in C#

后端 未结 30 2130
生来不讨喜
生来不讨喜 2020-11-21 05:59

Given a specific DateTime value, how do I display relative time, like:

  • 2 hours ago
  • 3 days ago
  • a month ago
30条回答
  •  孤独总比滥情好
    2020-11-21 06:26

    I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. Send your specific date, and get its value in string form:

    public string RelativeDateTimeCount(DateTime inputDateTime)
    {
        string outputDateTime = string.Empty;
        TimeSpan ts = DateTime.Now - inputDateTime;
    
        if (ts.Days > 7)
        { outputDateTime = inputDateTime.ToString("MMMM d, yyyy"); }
    
        else if (ts.Days > 0)
        {
            outputDateTime = ts.Days == 1 ? ("about 1 Day ago") : ("about " + ts.Days.ToString() + " Days ago");
        }
        else if (ts.Hours > 0)
        {
            outputDateTime = ts.Hours == 1 ? ("an hour ago") : (ts.Hours.ToString() + " hours ago");
        }
        else if (ts.Minutes > 0)
        {
            outputDateTime = ts.Minutes == 1 ? ("1 minute ago") : (ts.Minutes.ToString() + " minutes ago");
        }
        else outputDateTime = "few seconds ago";
    
        return outputDateTime;
    }
    

提交回复
热议问题