How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

后端 未结 25 1907
遥遥无期
遥遥无期 2020-11-22 12:57

The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

e.g.<

25条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 13:33

    I haven't checked (although it wouldn't be hard to), but I think that Stack Exchange sites use the jquery.timeago plugin to create these time strings.


    It's quite easy to use the plugin, and it's clean and updates automatically.

    Here's a quick sample (from the plugin's home page):

    First, load jQuery and the plugin:

    Now, let's 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: about a year ago which yields: about a year ago. As time passes, the timestamps will automatically update.

提交回复
热议问题