Calculate relative time in C#

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

    Here's how I do it

    var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
    double delta = Math.Abs(ts.TotalSeconds);
    
    if (delta < 60)
    {
      return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
    }
    if (delta < 60 * 2)
    {
      return "a minute ago";
    }
    if (delta < 45 * 60)
    {
      return ts.Minutes + " minutes ago";
    }
    if (delta < 90 * 60)
    {
      return "an hour ago";
    }
    if (delta < 24 * 60 * 60)
    {
      return ts.Hours + " hours ago";
    }
    if (delta < 48 * 60 * 60)
    {
      return "yesterday";
    }
    if (delta < 30 * 24 * 60 * 60)
    {
      return ts.Days + " days ago";
    }
    if (delta < 12 * 30 * 24 * 60 * 60)
    {
      int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
      return months <= 1 ? "one month ago" : months + " months ago";
    }
    int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
    return years <= 1 ? "one year ago" : years + " years ago";
    

    Suggestions? Comments? Ways to improve this algorithm?

提交回复
热议问题