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

后端 未结 25 2038
遥遥无期
遥遥无期 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: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"
    

提交回复
热议问题