Javascript确定日期并输出“时间”(如果今天是今天),“昨天”(昨天)以及实际日期(如果在此之前)

Mik*_*ike 5 javascript string time date trim

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

今天在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?

xbl*_*itz 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
    }
}
Run Code Online (Sandbox Code Playgroud)

比你应该能够得到这样的日期:

getDisplayDate(2013,01,14);
Run Code Online (Sandbox Code Playgroud)