我正在做一些日期庫的增強,它已經返回日期單位的差異,如這個問題的標題。我希望它返回相對單位。我寫了一些代碼,但感覺就像我在數學的錯誤結尾工作。相對日期:1/1/1981 01:01:01 - 1/1/1980 = 1y 366d等,想要1y 1d等
注意:忘記閏年和其他DateTime錯綜複雜。這是一個不嚴格的應用程序。
這裏是正在考慮的代碼。
// get ms between UTC dates and make into "difference" date
var iDiffMS = dt2.valueOf() - dt1.valueOf();
var dtDiff = new Date(iDiffMS);
// calc various diffs
var nYears = dt2.getUTCFullYear() - dt1.getUTCFullYear();
var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
var nQuarters = parseInt(nMonths/3); //<<-- different than VBScript, which watches rollover not completion
// these are in absolute terms, ie totals of unit differences, 1/2/1981 - 1/1/1980 = 1y 366d
var nMilliseconds = iDiffMS;
var nSeconds = parseInt(iDiffMS/1000);
var nMinutes = parseInt(nSeconds/60);
var nHours = parseInt(nMinutes/60);
var nDays = parseInt(nHours/24); // <-- now fixed for DST switch days
var nWeeks = parseInt(nDays/7);
// save absolutes
var nYears0=nYears;
var nMonths0=nMonths;
var nQuarters0=nQuarters;
var nWeeks0=nWeeks;
var nDays0=nDays;
var nHours0=nHours;
var nMinutes0=nMinutes;
var nSeconds0=nSeconds;
// HERE! go from absolute to relative, 1/2/1981 - 1/1/1980 = 1y 1d etc, not 1y 366d etc
nQuarters -=nYears0*4;
nMonths -=nYears0*12;
nWeeks -=parseInt((nYears0*52)+(nMonths0*(365.25/52)));
nCalWeeks -=parseInt((nYears0*52)+(nMonths0*(365.25/52)));
nQuarters -=nYears0*4;
nDays -=parseInt((nYears0*365.25) +(nMonths*(365.25/12)));
nHours -=parseInt((nYears0*365.25*24) +(nMonths*(365.25/12*24)) +(nDays*24));
nMinutes -=parseInt((nYears0*365.25*24*60) +(nMonths*(365.25/12*24*60)) +(nDays*24*60) +(nHours*60));
nSeconds -=parseInt((nYears0*365.25*24*60*60) +(nMonths*(365.25/12*24*60*60)) +(nDays*24*60*60) +(nHours*60*60) +(nMinutes*60));
nMilliseconds -=parseInt((nYears0*365.25*24*60*60*1000) +(nMonths*(365.25/12*24*60*60*1000))+(nDays*24*60*60*1000) +(nHours*60*60*1000) +(nMinutes*60*1000) + (nSeconds*1000));
// END
按照你想要的格式,什麼是正確的答案爲3/3/1981 - 1/1/1980?你想要'1年,2個月,2天'嗎? –
是的,只是把以毫秒爲單位的差異(1970年後),並將其轉換回 – maraca
是,1年,2個月,2天,X小時,等 –