Calculate relative time in C#

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

    jquery.timeago plugin

    Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.

    Benefits:

    • Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
    • You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.
    • You get to use microformats like the cool kids.

    Just attach it to your timestamps on DOM ready:

    jQuery(document).ready(function() {
        jQuery('abbr.timeago').timeago();
    });
    

    This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title:

    July 17, 2008
    

    into something like this:

    4 months ago
    

    which yields: 4 months ago. As time passes, the timestamps will automatically update.

    Disclaimer: I wrote this plugin, so I'm biased.

提交回复
热议问题