Calculate relative time in C#

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

    You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:

    public string GetRelativeTime(DateTime timeStamp)
    {
        return string.Format("", timeStamp.ToFileTimeUtc());
    }
    

    You could even add a NOSCRIPT block there and just perform a ToString().

提交回复
热议问题