Javascript DateDiff

Fra*_* G. 8 javascript datediff date

我遇到DateDiff函数的问题.我想弄清楚两个日期/时间之间的差异.我已经阅读了这篇文章(在Javascript中计算日期差异的最佳方法是什么),我也看了这个教程(http://www.javascriptkit.com/javatutors/datedifference.shtml),但我似乎无法得到它.

这是我试图开始工作但没有成功.有人可以告诉我我在做什么以及如何简化这一点.似乎有点过度编码......?

//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);
Run Code Online (Sandbox Code Playgroud)

Fra*_* G. 11

对于那些想要一个工作示例的人来说,这是一个简单的DateDiff ex,它以负值(已经过去的日期)或正(日期即将到来)告诉日期差异.

编辑:我更新了这个脚本,所以它会为你做腿部工作并将结果转换为-10,这意味着日期已经过去了.为currDate和iniPastedDate输入你自己的日期,你应该好好去!

//Set the two dates
var currentTime   = new Date()
var currDate      = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.

//currDate = 8/17/12 and iniPastedDate = 8/7/12

function DateDiff(date1, date2) {
    var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
    return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value      
}

//Write out the returning value should be using this example equal -10 which means 
//it has passed by ten days. If its positive the date is coming +10.    
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
Run Code Online (Sandbox Code Playgroud)


pim*_*vdb 5

您的第一次尝试先添加,然后减去.你无论如何都不能减去字符串,因此产生了收益NaN.

第二个特里没有结束).除此之外,你正在呼唤getTime字符串.你需要使用new Date(...).getTime().请注意,在减去日期时,您会得到以毫秒为单位的结果.您可以通过取出整天/小时/等来格式化.

  • @Frank G:那是几毫秒.如果你将它转换为天数确实是7天前:`-604800000 /(24*60*60*1000)=== -7`. (2认同)