JavaScript判断日期并输出"时间"(如果是今天),"昨天"(如果是昨天),如果是之前的日期则输出实际日期。

8
我正在创建一个简单的电子邮件客户端,我希望收件箱以以下格式显示接收到邮件的日期:
今天 13:17
昨天 20:38
1月13日 17:15
2012年12月21日 @ 18:12
我从数据库中检索数据,将其输出到xml(以便所有操作都可以通过AJAX完成),并在 <ul><li> 格式中打印结果。
日期和时间分别以以下格式存储: Date(y-m-d) Time(H:i:s) 目前,我发现PHP可以实现类似的功能。在这里 - PHP: date "Yesterday", "Today" 这种功能是否可以使用javascript实现?
3个回答

3
我会用类似这样的方式进行操作。
function getDisplayDate(year, month, day) {
    today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);
    compDate = new Date(year,month-1,day); // month - 1 because January == 0
    diff = today.getTime() - compDate.getTime(); // get the difference between today(at 00:00:00) and the date
    if (compDate.getTime() == today.getTime()) {
        return "Today";
    } else if (diff <= (24 * 60 * 60 *1000)) {
        return "Yesterday";
    } else { 
        return compDate.toDateString(); // or format it what ever way you want
    }
}

如果一切正常,您应该能够像这样获取日期:
getDisplayDate(2013,01,14);

我该如何更改格式,以便它能够读取为“Sun 12 Aug 2012”? - Michael

1
这是两个答案的汇编(应该会给你一个很好的开端): 我建议阅读两个问题和回答,以更好地了解正在发生的事情。
function DateDiff(date1, date2) {
    return dhm(date1.getTime() - date2.getTime());
}

function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

var yesterdaysDate = new Date("01/14/2013");
var todaysDate = new Date("01/15/2013");

// You'll want to perform your logic on this result
var diff = DateDiff(yesterdaysDate, todaysDate); // Result: -1.00

1
function getDisplayDate(year, month, day) {
    today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);
    compDate = new Date(year,month-1,day); // month - 1 because January == 0
    diff = today.getTime() - compDate.getTime(); // get the difference between today(at 00:00:00) and the date
    if (compDate.getTime() == today.getTime()) {
        return "Today";
    } else if (diff <= (24 * 60 * 60 *1000)) {
        return "Yesterday";
    } else { 
        //return compDate.toDateString(); // or format it what ever way you want
        year = compDate.getFullYear();
        month = compDate.getMonth();
        months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
        day = compDate.getDate();
        d = compDate.getDay();
        days = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

        var formattedDate = days[d] + " " + day + " " + months[month] + " " + year;
        return formattedDate;
    }
}

这是@xblitz的答案,我进行了格式化以便以美观的方式显示日期。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接