8

我遇到了 DateDiff 函数的问题。我试图找出两个日期/时间之间的差异。我已经阅读了这篇文章(What's the best way to calculate date Difference in 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);
4

4 回答 4

12

好的,对于那些想要一个工作示例的人来说,这里是一个简单的 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...
于 2012-08-17T10:22:15.300 回答
5

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

第二次尝试没有关闭)。除此之外,您正在调用getTime字符串。你需要使用new Date(...).getTime(). 请注意,减去日期时,您会以毫秒为单位获得结果。您可以通过取出全天/小时/等来格式化它。

于 2012-08-17T10:03:15.333 回答
2
function setDateWeek(setDay){
    var d = new Date();
    d.setDate(d.getDate() - setDay); // <-- add this
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();
    return curr_date + "-" + curr_month + "-" + curr_year;
}


setDateWeek(1);
于 2014-04-21T07:13:02.733 回答
-2

无需包含 JQuery 或任何其他第三方库。

在标题标签中指定您的输入日期格式。

HTML:

< script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">

使用javascript函数:

IP_dateDiff(strDate1,strDate2,strDateFormat,debug[true/false])

alert(IP_dateDiff('11-12-2014','12-12-2014','DD-MM-YYYY',false));

IP_dateDiff 函数将返回天数。

于 2015-09-02T07:39:32.677 回答