Calculate relative time in C#

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

    @jeff

    IMHO yours seems a little long. However it does seem a little more robust with support for "yesterday" and "years". But in my experience when this is used, the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So, I usually elect to keep this short and simple.

    This is the method I am currently using in one of my websites. This returns only a relative day, hour and time. And then the user has to slap on "ago" in the output.

    public static string ToLongString(this TimeSpan time)
    {
        string output = String.Empty;
    
        if (time.Days > 0)
            output += time.Days + " days ";
    
        if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)
            output += time.Hours + " hr ";
    
        if (time.Days == 0 && time.Minutes > 0)
            output += time.Minutes + " min ";
    
        if (output.Length == 0)
            output += time.Seconds + " sec";
    
        return output.Trim();
    }
    

提交回复
热议问题