此代码在chrome和firefox中运行良好,但它在IE和Safari中不起作用。它在IE中返回NAN,在safair中返回无效日期。
var date = new Date("2012-10-17T08:15:19.500-05:00");
var now = new Date();
var difference = now - date;
document.write( "Date: " + date.toLocaleString() + "<br/>");
document.write( "Now: " + now.toLocaleString() + "<br/>");
document.write( "Difference: " + differenceToString(difference) );
function differenceToString(milliseconds) {
var seconds = milliseconds / 1000;
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = Math.floor((((seconds % 31536000) % 86400) % 3600) % 60);
return numyears + " years, " + numdays + " days, " + numhours + " hours, " + numminutes + " minutes, " + numseconds + " seconds";
}
任何想法都会有很大的帮助。
由于
答案 0 :(得分:0)
您忘记了时区偏移之前的Z
,根据language specification获取有效的JS解析日期 - YYYY-MM-DDTHH:mm:ss.sssZ±hh:mm
是only format it must accept。尝试
var date = new Date("2012-10-17T08:15:19.500Z-05:00");
…