How to calculate the number of days between two dates?
This question already has an answer here:
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
这是一个这样的功能:
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
链接地址: http://www.djcxy.com/p/36710.html
下一篇: 如何计算两个日期之间的天数?