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

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

    from now, unix timestamp param,

    function timeSince(ts){
        now = new Date();
        ts = new Date(ts*1000);
        var delta = now.getTime() - ts.getTime();
    
        delta = delta/1000; //us to s
    
        var ps, pm, ph, pd, min, hou, sec, days;
    
        if(delta<=59){
            ps = (delta>1) ? "s": "";
            return delta+" second"+ps
        }
    
        if(delta>=60 && delta<=3599){
            min = Math.floor(delta/60);
            sec = delta-(min*60);
            pm = (min>1) ? "s": "";
            ps = (sec>1) ? "s": "";
            return min+" minute"+pm+" "+sec+" second"+ps;
        }
    
        if(delta>=3600 && delta<=86399){
            hou = Math.floor(delta/3600);
            min = Math.floor((delta-(hou*3600))/60);
            ph = (hou>1) ? "s": "";
            pm = (min>1) ? "s": "";
            return hou+" hour"+ph+" "+min+" minute"+pm;
        } 
    
        if(delta>=86400){
            days = Math.floor(delta/86400);
            hou =  Math.floor((delta-(days*86400))/60/60);
            pd = (days>1) ? "s": "";
            ph = (hou>1) ? "s": "";
            return days+" day"+pd+" "+hou+" hour"+ph;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 13:11

    I write one with js and python, used in two projects, very nice and simple: a simple library (less then 2kb) used to format date with *** time ago statement.

    simple, small, easy used, and well tested.

    1. npm install timeago.js

    2. import timeago from 'timeago.js'; // or use script tag

    3. use api format.

    Sample:

    var timeagoIns  = timeago();
    timeagoIns .format('2016-06-12');
    

    Also you can render in real-time.

    var timeagoIns = timeago();
    timeagoIns.render(document.querySelectorAll('time'));
    
    0 讨论(0)
  • 2020-11-22 13:11
    function dateToHowManyAgo(stringDate){
        var currDate = new Date();
        var diffMs=currDate.getTime() - new Date(stringDate).getTime();
        var sec=diffMs/1000;
        if(sec<60)
            return parseInt(sec)+' second'+(parseInt(sec)>1?'s':'')+' ago';
        var min=sec/60;
        if(min<60)
            return parseInt(min)+' minute'+(parseInt(min)>1?'s':'')+' ago';
        var h=min/60;
        if(h<24)
            return parseInt(h)+' hour'+(parseInt(h)>1?'s':'')+' ago';
        var d=h/24;
        if(d<30)
            return parseInt(d)+' day'+(parseInt(d)>1?'s':'')+' ago';
        var m=d/30;
        if(m<12)
            return parseInt(m)+' month'+(parseInt(m)>1?'s':'')+' ago';
        var y=m/12;
        return parseInt(y)+' year'+(parseInt(y)>1?'s':'')+' ago';
    }
    console.log(dateToHowManyAgo('2019-11-07 19:17:06'));
    
    0 讨论(0)
  • 2020-11-22 13:12

    An ES6 version of the code provided by @user1012181

    // Epochs
    const epochs = [
        ['year', 31536000],
        ['month', 2592000],
        ['day', 86400],
        ['hour', 3600],
        ['minute', 60],
        ['second', 1]
    ];
    
    
    // Get duration
    const getDuration = (timeAgoInSeconds) => {
        for (let [name, seconds] of epochs) {
            const interval = Math.floor(timeAgoInSeconds / seconds);
    
            if (interval >= 1) {
                return {
                    interval: interval,
                    epoch: name
                };
            }
        }
    };
    
    
    // Calculate
    const timeAgo = (date) => {
        const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
        const {interval, epoch} = getDuration(timeAgoInSeconds);
        const suffix = interval === 1 ? '' : 's';
    
        return `${interval} ${epoch}${suffix} ago`;
    };
    

    Edited with @ibe-vanmeenen suggestions. (Thanks !)

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

    Although the question was asked quite long time ago, writing this answer with hope it will help somebody.

    Pass the date you want to start to count from. Using moment().fromNow() of momentjs: (See more information here)

    getRelativeTime(date) {
        const d = new Date(date * 1000);
        return moment(d).fromNow();
    }
    

    If you want to change information provided for dates fromNow you write your custom relative time for moment.

    For example, in my own case I wanted to print 'one month ago' instead of 'a month ago' (provided by moment(d).fromNow()). In this case, you can write something given below.

    moment.updateLocale('en', {
        relativeTime: {
            future: 'in %s',
            past: '%s ago',
            s: 'a few seconds',
            ss: '%d seconds',
            m: '1 m',
            mm: '%d minutes',
            h: '1 h',
            hh: '%d hours',
            d: '1 d',
            dd: '%d days',
            M: '1 month',
            MM: '%d months',
            y: '1 y',
            yy: '%d years'
        }
    });
    

    NOTE: I wrote my code for project in Angular 6

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

    I have modified Sky Sanders' version. The Math.floor(...) operations are evaluated in the if block

           var timeSince = function(date) {
                var seconds = Math.floor((new Date() - date) / 1000);
                var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                if (seconds < 5){
                    return "just now";
                }else if (seconds < 60){
                    return seconds + " seconds ago";
                }
                else if (seconds < 3600) {
                    minutes = Math.floor(seconds/60)
                    if(minutes > 1)
                        return minutes + " minutes ago";
                    else
                        return "1 minute ago";
                }
                else if (seconds < 86400) {
                    hours = Math.floor(seconds/3600)
                    if(hours > 1)
                        return hours + " hours ago";
                    else
                        return "1 hour ago";
                }
                //2 days and no more
                else if (seconds < 172800) {
                    days = Math.floor(seconds/86400)
                    if(days > 1)
                        return days + " days ago";
                    else
                        return "1 day ago";
                }
                else{
    
                    //return new Date(time).toLocaleDateString();
                    return date.getDate().toString() + " " + months[date.getMonth()] + ", " + date.getFullYear();
                }
            }
    
    0 讨论(0)
提交回复
热议问题