4 回答

TA貢獻1821條經驗 獲得超5個贊
在撰寫本文時,只有其中一個答案正確處理DST(夏令時)轉換。以下是位于加利福尼亞州的系統的結果:
1/1/2013- 3/10/2013- 11/3/2013-
User Formula 2/1/2013 3/11/2013 11/4/2013 Result
--------- --------------------------- -------- --------- --------- ---------
Miles (d2 - d1) / N 31 0.9583333 1.0416666 Incorrect
some Math.floor((d2 - d1) / N) 31 0 1 Incorrect
fuentesjr Math.round((d2 - d1) / N) 31 1 1 Correct
toloco Math.ceiling((d2 - d1) / N) 31 1 2 Incorrect
N = 86400000
雖然Math.round返回了正確的結果,但我認為它有些笨重。相反,通過在DST開始或結束時明確說明UTC偏移的變化,我們可以使用精確算術:
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
alert(daysBetween($('#first').val(), $('#second').val()));
說明
JavaScript日期計算很棘手,因為Date對象在UTC內部存儲時間,而不是本地時間。例如,3/10/2013 12:00 AM太平洋標準時間(UTC-08:00)存儲為3/10/2013 8:00 AM UTC和3/11/2013 12:00 AM Pacific Daylight Time( UTC-07:00)存儲為3/11/2013 7:00 AM UTC。在這一天午夜到午夜當地時間只有23小時在UTC!
雖然當地時間的一天可能有多于或少于24小時,但UTC的一天總是正好24小時。1daysBetween上面顯示的方法利用了這一事實,首先要求treatAsUTC在減去和分割之前調整本地時間到午夜UTC。

TA貢獻1853條經驗 獲得超9個贊
獲得兩個日期之間差異的最簡單方法:
var diff = Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000);
您可以獲得差異天數(如果無法解析其中一個或兩個,則為NaN)。解析日期以毫秒為單位給出結果,并且按天劃分它需要將其除以24 * 60 * 60 * 1000
如果你想要它除以天,小時,分鐘,秒和毫秒:
function dateDiff( str1, str2 ) {
var diff = Date.parse( str2 ) - Date.parse( str1 );
return isNaN( diff ) ? NaN : {
diff : diff,
ms : Math.floor( diff % 1000 ),
s : Math.floor( diff / 1000 % 60 ),
m : Math.floor( diff / 60000 % 60 ),
h : Math.floor( diff / 3600000 % 24 ),
d : Math.floor( diff / 86400000 )
};
}
這是我的重構版James版本:
function mydiff(date1,date2,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
date1 = new Date(date1);
date2 = new Date(date2);
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return date2.getFullYear() - date1.getFullYear();
case "months": return (
( date2.getFullYear() * 12 + date2.getMonth() )
-
( date1.getFullYear() * 12 + date1.getMonth() )
);
case "weeks" : return Math.floor(timediff / week);
case "days" : return Math.floor(timediff / day);
case "hours" : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}
添加回答
舉報