我正在创建一个简单的电子邮件客户端,我希望收件箱以以下格式显示收到电子邮件的日期:
今天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吗?
答案 0 :(得分: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 :(得分: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
}
}
比你应该得到这样的日期:
getDisplayDate(2013,01,14);
答案 2 :(得分: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回答我的格式,以一种很好的方式显示日期。