Javascript 日期差异

标签 javascript date datediff

我在使用 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);

最佳答案

对于那些想要一个工作示例的人来说,这里有一个简单的 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...

关于Javascript 日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12003660/

相关文章:

javascript - 如何将文件名设置为与数据库中的对象 ID 相同?

javascript - 未捕获的类型错误 : Object function () has no method 'replace'

javascript - 检查 native 浏览器对延迟加载图像的支持

c++ - 视觉 C++ : Compare Dates

mysql - 在 sql 结果中填充空日期的最直接方法是什么(在 mysql 或 perl 端)?

MySQL:以月为单位的日期差异(即使 'month' < 30 天也应计为 1)

javascript - 有没有办法在将滚动位置保持在底部的同时使用页脚的滑动切换?

sql - 在 dplyr (SQL) 中处理日期和连接字符串

java - 从 System.nanoTime() 生成日期

mysql - 连接两个表,日期间隔为前 3 天和后 3 天