4 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
在撰寫(xiě)本文時(shí),只有其中一個(gè)答案正確處理DST(夏令時(shí))轉(zhuǎn)換。以下是位于加利福尼亞州的系統(tǒng)的結(jié)果:
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返回了正確的結(jié)果,但我認(rèn)為它有些笨重。相反,通過(guò)在DST開(kāi)始或結(jié)束時(shí)明確說(shuō)明UTC偏移的變化,我們可以使用精確算術(shù):
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()));
說(shuō)明
JavaScript日期計(jì)算很棘手,因?yàn)镈ate對(duì)象在UTC內(nèi)部存儲(chǔ)時(shí)間,而不是本地時(shí)間。例如,3/10/2013 12:00 AM太平洋標(biāo)準(zhǔn)時(shí)間(UTC-08:00)存儲(chǔ)為3/10/2013 8:00 AM UTC和3/11/2013 12:00 AM Pacific Daylight Time( UTC-07:00)存儲(chǔ)為3/11/2013 7:00 AM UTC。在這一天午夜到午夜當(dāng)?shù)貢r(shí)間只有23小時(shí)在UTC!
雖然當(dāng)?shù)貢r(shí)間的一天可能有多于或少于24小時(shí),但UTC的一天總是正好24小時(shí)。1daysBetween上面顯示的方法利用了這一事實(shí),首先要求treatAsUTC在減去和分割之前調(diào)整本地時(shí)間到午夜UTC。

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
獲得兩個(gè)日期之間差異的最簡(jiǎn)單方法:
var diff = Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000);
您可以獲得差異天數(shù)(如果無(wú)法解析其中一個(gè)或兩個(gè),則為NaN)。解析日期以毫秒為單位給出結(jié)果,并且按天劃分它需要將其除以24 * 60 * 60 * 1000
如果你想要它除以天,小時(shí),分鐘,秒和毫秒:
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 )
};
}
這是我的重構(gòu)版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;
}
}
添加回答
舉報(bào)