我遇到了DateDiff函数的问题。我试图找出两个日期/时间之间的差异。我已阅读这篇文章(What's the best way to calculate date difference in Javascript),我也看了这个教程(http://www.javascriptkit.com/javatutors/datedifference.shtml),但我似乎无法得到它。Javascript DateDiff
下面是我试图去工作没有成功。有人可以告诉我我在做什么以及如何简化这一点。似乎有点过分编码...?
//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";
//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);
//Try this function...
function DateDiff(date1, date2) {
return date1.getTime() - date2.getTime();
}
//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
正如你所说,它会显示一个负值。这是否正确,因为它显示了负值。 \t \t document.write(new Date(iniremDate)-new Date(currDate)); \t \t \t 功能\t DateDiff的(DATE1,DATE2){ \t \t返回date1.getTime() - date2.getTime(); \t \t} \t \t \t \t 文件撰写\t(DateDiff的(新日期(iniremDate),新的日期(currDate))); – 2012-08-17 10:15:06
因为'iniremDate'是8月10日,现在是17日,你显然会得到一个负值。如果你想减去相反的,只需从'date2'减去'date1'。 – pimvdb 2012-08-17 10:16:46
返回值是-604800000我认为这意味着它已经很久以前在几秒钟内通过了? – 2012-08-17 10:16:46