我正在计算“从”和“到”日期之间的天数。例如,如果起始日期是 13/04/2010 而截止日期是 15/04/2010,结果应该是
如何使用 JavaScript 获得结果?
如何计算两个日期之间的天数?
IT技术
javascript
html
date
2021-01-18 15:38:01
6个回答
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
这是一个执行此操作的函数:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
这是我使用的。如果您只是减去日期,则它不会跨越夏令时边界(例如,4 月 1 日至 4 月 30 日或 10 月 1 日至 10 月 31 日)。这会减少所有时间以确保您有一天并通过使用 UTC 消除任何 DST 问题。
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;
}
这是我的实现:
function daysBetween(one, another) {
return Math.round(Math.abs((+one) - (+another))/8.64e7);
}
+<date>
对整数表示进行类型强制,与<date>.getTime()
和8.64e7
是一天中的毫秒数具有相同的效果。
调整以允许夏令时差异。试试这个:
function daysBetween(date1, date2) {
// adjust diff for for daylight savings
var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
// apply the tz offset
date2.addHours(hoursToAdjust);
// 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)
}
// you'll want this addHours function too
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}