6

我正在创建一个简单的电子邮件客户端,我希望收件箱以以下格式显示收到电子邮件的日期:

今天 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:日期“昨天”,“今天”

这可能使用javascript吗?

4

3 回答 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);
于 2013-01-15T14:23:54.320 回答
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
于 2013-01-15T13:57:26.883 回答
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 用我的格式回答以一种很好的方式显示日期。

于 2013-01-15T15:36:48.753 回答