且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算javascript中两个日期之间的天数

更新时间:2022-11-13 14:01:14

使用

var firstDate = new Date(); // Todays date
var secondDate = new Date(2011,08,19, 11,49,01);

var diffDays = (firstDate.getDate() - secondDate.getDate());

它显示NAN,因为你的构造函数是错误的。通过在原始代码中提醒secondDate来检查自己

It was showing NAN as your constructor is wrong. check yourself by alerting secondDate in your original code

编辑:如果两个日期在同一个月,则上述代码将起作用,一般情况下

Edit : above code will work if both dates are in same month, for general case

var oneDay  = 24*60*60*1000;
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / oneDay);

此外,这将给出结果作为日期的一小部分,因此如果您想计算整个日期,您可以使用Math.ceil或Math.floor

Also this will give result as fraction of date, so if you want to count whole dates you can use Math.ceil or Math.floor