如何计算两个日期之间的天数?我正在计算“从”到“日期”之间的天数。例如,如果开始日期为13/04/2010,而截止日期为15/04/2010,则结果应该是如何使用JavaScript获得结果?
3 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
var oneDay = 24*60*60*1000; // hours*minutes*seconds*millisecondsvar firstDate = new Date(2008,01,12);var secondDate = new Date(2008,01,22); var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
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);}
慕标5832272
TA贡献1966条经验 获得超4个赞
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) - Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
function DaysBetween(StartDate, EndDate) { // The number of milliseconds in all UTC days (no DST) const oneDay = 1000 * 60 * 60 * 24; // A day in UTC always lasts 24 hours (unlike in other time formats) const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()); const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate()); // so it's safe to divide by 24 hours return (start - end) / oneDay;}
添加回答
举报
0/150
提交
取消