Calculate relative time in C#

后端 未结 30 2126
生来不讨喜
生来不讨喜 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:23

    You can use TimeAgo extension as below:

    public static string TimeAgo(this DateTime dateTime)
    {
        string result = string.Empty;
        var timeSpan = DateTime.Now.Subtract(dateTime);
     
        if (timeSpan <= TimeSpan.FromSeconds(60))
        {
            result = string.Format("{0} seconds ago", timeSpan.Seconds);
        }
        else if (timeSpan <= TimeSpan.FromMinutes(60))
        {
            result = timeSpan.Minutes > 1 ? 
                String.Format("about {0} minutes ago", timeSpan.Minutes) :
                "about a minute ago";
        }
        else if (timeSpan <= TimeSpan.FromHours(24))
        {
            result = timeSpan.Hours > 1 ? 
                String.Format("about {0} hours ago", timeSpan.Hours) : 
                "about an hour ago";
        }
        else if (timeSpan <= TimeSpan.FromDays(30))
        {
            result = timeSpan.Days > 1 ? 
                String.Format("about {0} days ago", timeSpan.Days) : 
                "yesterday";
        }
        else if (timeSpan <= TimeSpan.FromDays(365))
        {
            result = timeSpan.Days > 30 ? 
                String.Format("about {0} months ago", timeSpan.Days / 30) : 
                "about a month ago";
        }
        else
        {
            result = timeSpan.Days > 365 ? 
                String.Format("about {0} years ago", timeSpan.Days / 365) : 
                "about a year ago";
        }
     
        return result;
    }
    

    Or use jQuery plugin with Razor extension from Timeago.

提交回复
热议问题