问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。

e.g.

1分钟前 1小时前 1天前 1个月前 一年前


当前回答

我用js和python写了一个,在两个项目中使用,非常漂亮和简单:一个简单的库(少于2kb),用于*** time ago语句格式化日期。

简单,小巧,易于使用,并且经过良好测试。

NPM安装timeago.js 从timeago.js导入timeago;//或使用脚本标签 使用API格式。

示例:

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

你也可以实时渲染。

var timeagoIns = timeago();
timeagoIns.render(document.querySelectorAll('time'));

其他回答

从现在开始,Unix时间戳参数

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;
    }

}

在这种情况下可能有点过头了,但如果有机会,moment.js真的很棒!

js是一个javascript datetime库,在这种情况下使用它,你需要做:

moment(yourdate).fromNow()

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

2018附录:Luxon是一个新的现代图书馆,可能值得一看!

2022年附录:Day.js是一个较新的库,比Luxon轻80%左右,具有类似的功能。

 I achieve this by following method

   timeAgo = (date) => {
            var ms = (new Date()).getTime() - date.getTime();
            var seconds = Math.floor(ms / 1000);
            var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);
        var months = Math.floor(days / 30);
        var years = Math.floor(months / 12);
    
        if (ms === 0) {
            return 'Just now';
        } if (seconds < 60) {
            return seconds + ' seconds Ago';
        } if (minutes < 60) {
            return minutes + ' minutes Ago';
        } if (hours < 24) {
            return hours + ' hours Ago';
        } if (days < 30) {
            return days + ' days Ago';
        } if (months < 12) {
            return months + ' months Ago';
        } else {
            return years + ' years Ago';
        }
    
    }
    
        console.log(timeAgo(new Date()));
        console.log(timeAgo(new Date('Jun 27 2020 10:12:19')));
        console.log(timeAgo(new Date('Jun 27 2020 00:12:19')));
        console.log(timeAgo(new Date('May 28 2020 13:12:19')));
        console.log(timeAgo(new Date('May 28 2017 13:12:19')));

这应该正确地处理任何有效的时间戳,包括Date.now()、单数单位和未来日期。我漏掉了月份,但是这些月份应该很容易加进去。我尽量保持它的可读性。

function getTimeInterval(date) { let seconds = Math.floor((Date.now() - date) / 1000); let unit = "second"; let direction = "ago"; if (seconds < 0) { seconds = -seconds; direction = "from now"; } let value = seconds; if (seconds >= 31536000) { value = Math.floor(seconds / 31536000); unit = "year"; } else if (seconds >= 86400) { value = Math.floor(seconds / 86400); unit = "day"; } else if (seconds >= 3600) { value = Math.floor(seconds / 3600); unit = "hour"; } else if (seconds >= 60) { value = Math.floor(seconds / 60); unit = "minute"; } if (value != 1) unit = unit + "s"; return value + " " + unit + " " + direction; } console.log(getTimeInterval(Date.now())); // 0 seconds ago console.log(getTimeInterval(Date.now() + 1000)); // 1 second from now console.log(getTimeInterval(Date.now() - 1000)); // 1 second ago console.log(getTimeInterval(Date.now() + 60000)); // 1 minute from now console.log(getTimeInterval(Date.now() - 120000)); // 2 minutes ago console.log(getTimeInterval(Date.now() + 120000)); // 2 minutes from now console.log(getTimeInterval(Date.now() + 3600000)); // 1 hour from now console.log(getTimeInterval(Date.now() + 360000000000)); // 11 years from now console.log(getTimeInterval(0)); // 49 years ago

这将显示你过去和以前的时间格式,如“2天前”“从现在开始10分钟”,你可以传递给它一个日期对象,数字时间戳或日期字符串

function time_ago(time) { switch (typeof time) { case 'number': break; case 'string': time = +new Date(time); break; case 'object': if (time.constructor === Date) time = time.getTime(); break; default: time = +new Date(); } var time_formats = [ [60, 'seconds', 1], // 60 [120, '1 minute ago', '1 minute from now'], // 60*2 [3600, 'minutes', 60], // 60*60, 60 [7200, '1 hour ago', '1 hour from now'], // 60*60*2 [86400, 'hours', 3600], // 60*60*24, 60*60 [172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2 [604800, 'days', 86400], // 60*60*24*7, 60*60*24 [1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2 [2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7 [4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2 [29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4 [58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2 [2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12 [5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2 [58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100 ]; var seconds = (+new Date() - time) / 1000, token = 'ago', list_choice = 1; if (seconds == 0) { return 'Just now' } if (seconds < 0) { seconds = Math.abs(seconds); token = 'from now'; list_choice = 2; } var i = 0, format; while (format = time_formats[i++]) if (seconds < format[0]) { if (typeof format[2] == 'string') return format[list_choice]; else return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token; } return time; } var aDay = 24 * 60 * 60 * 1000; console.log(time_ago(new Date(Date.now() - aDay))); console.log(time_ago(new Date(Date.now() - aDay * 2)));