【发布时间】:2015-05-02 01:31:39
【问题描述】:
我正在对日期库进行一些增强,该库已经返回日期单位的差异,如本问题的标题所示。我希望它返回相对单位。我已经写了一些代码,但感觉好像我在计算错误的结果。
注意:忘记闰年和其他复杂的日期时间。这适用于不严格的应用程序。
这是正在考虑的代码。
// 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
【问题讨论】:
-
在您想要的格式中,1981 年 3 月 3 日至 1980 年 1 月 1 日的正确答案是什么?你想要“1年2个月2天”吗?
-
是的,只需以毫秒为单位(1970 年之后)将其转换回来
-
是的,1 年、2 个月、2 天、x 小时等
标签: javascript algorithm date datetime time