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

后端 未结 25 1595
遥遥无期
遥遥无期 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条回答
  • 2020-11-22 13:17

    Simple and readable version:

    const NOW = new Date()
    const times = [["second", 1], ["minute", 60], ["hour", 3600], ["day", 86400], ["week", 604800], ["month", 2592000], ["year", 31536000]]
    
    function timeAgo(date) {
        var diff = Math.round((NOW - date) / 1000)
        for (var t = 0; t < times.length; t++) {
            if (diff < times[t][1]) {
                if (t == 0) {
                    return "Just now"
                } else {
                    diff = Math.round(diff / times[t - 1][1])
                    return diff + " " + times[t - 1][0] + (diff == 1?" ago":"s ago")
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:18

    Answering 10 years old question to help the newcomers.

    We can use this package for that javascript-time-ago

     
    // Load locale-specific relative date/time formatting rules.
    import en from 'javascript-time-ago/locale/en'
     
    // Add locale-specific relative date/time formatting rules.
    TimeAgo.addLocale(en)
     
    // Create relative date/time formatter.
    const timeAgo = new TimeAgo('en-US')
     
    timeAgo.format(new Date())
    // "just now"
     
    timeAgo.format(Date.now() - 60 * 1000)
    // "a minute ago"
     
    timeAgo.format(Date.now() - 2 * 60 * 60 * 1000)
    // "2 hours ago"
     
    timeAgo.format(Date.now() - 24 * 60 * 60 * 1000)
    // "a day ago"
    
    0 讨论(0)
  • 2020-11-22 13:19

    function timeSince(date) {
    
      var seconds = Math.floor((new Date() - date) / 1000);
    
      var interval = seconds / 31536000;
    
      if (interval > 1) {
        return Math.floor(interval) + " years";
      }
      interval = seconds / 2592000;
      if (interval > 1) {
        return Math.floor(interval) + " months";
      }
      interval = seconds / 86400;
      if (interval > 1) {
        return Math.floor(interval) + " days";
      }
      interval = seconds / 3600;
      if (interval > 1) {
        return Math.floor(interval) + " hours";
      }
      interval = seconds / 60;
      if (interval > 1) {
        return Math.floor(interval) + " minutes";
      }
      return Math.floor(seconds) + " seconds";
    }
    var aDay = 24*60*60*1000;
    console.log(timeSince(new Date(Date.now()-aDay)));
    console.log(timeSince(new Date(Date.now()-aDay*2)));

    0 讨论(0)
  • 2020-11-22 13:20

    Might be an overkill in this case, but if the opportunity shows moment.js is just awesome!

    Moment.js is a javascript datetime library, to use it for such scenario, you'd do:

    moment(yourdate).fromNow()
    

    http://momentjs.com/docs/#/displaying/fromnow/

    2018 addendum: Luxon is a new modern library and might be worth a look!

    0 讨论(0)
  • 2020-11-22 13:20

    You might want to look at humanized_time_span: https://github.com/layam/js_humanized_time_span

    It's framework agnostic and fully customizable.

    Just download / include the script and then you can do this:

    humanized_time_span("2011-05-11 12:00:00")  
       => '3 hours ago'
    
    humanized_time_span("2011-05-11 12:00:00", "2011-05-11 16:00:00)  
       => '4 hours ago'
    

    or even this:

    var custom_date_formats = {
      past: [
        { ceiling: 60, text: "less than a minute ago" },
        { ceiling: 86400, text: "$hours hours, $minutes minutes and $seconds seconds ago" },
        { ceiling: null, text: "$years years ago" }
      ],
      future: [
        { ceiling: 60, text: "in less than a minute" },
        { ceiling: 86400, text: "in $hours hours, $minutes minutes and $seconds seconds time" },
        { ceiling: null, text: "in $years years" }
      ]
    }
    
    humanized_time_span("2010/09/10 10:00:00", "2010/09/10 10:00:05", custom_date_formats) 
      => "less than a minute ago"
    

    Read the docs for more info.

    0 讨论(0)
  • 2020-11-22 13:20

    Changed the function above to

    function timeSince(date) {
    
        var seconds = Math.floor(((new Date().getTime()/1000) - date)),
        interval = Math.floor(seconds / 31536000);
    
        if (interval > 1) return interval + "y";
    
        interval = Math.floor(seconds / 2592000);
        if (interval > 1) return interval + "m";
    
        interval = Math.floor(seconds / 86400);
        if (interval >= 1) return interval + "d";
    
        interval = Math.floor(seconds / 3600);
        if (interval >= 1) return interval + "h";
    
        interval = Math.floor(seconds / 60);
        if (interval > 1) return interval + "m ";
    
        return Math.floor(seconds) + "s";
    }
    

    Otherwise it would show things like "75 minutes" (between 1 and 2 hours). It also now assumes input date is a Unix timestamp.

    0 讨论(0)
提交回复
热议问题