几天来,我一直在努力解决这个确切的问题。终于做了一些我认为有用的东西。现在看起来像废话,草率的评论和愚蠢的 var 名称,明天我会进行清理。但我想无论如何我都会发布它以防万一你需要它。
编辑:我清理了代码并做了一个要点。在这里查看:https ://gist.github.com/4705863
EDIT2:该死的,发现了一个错误。我在上面。修复了BUG,现在可以正常使用了!
// Time difference function
function timeDiff(start, end) {
//today, now!
//Get the diff
var diff = end - start;
//Create numbers for dividing to get hour, minute and second diff
var units = [
1000 * 60 * 60 *24,
1000 * 60 * 60,
1000 * 60,
1000
];
var rv = []; // h, m, s array
//loop through d, h, m, s. we are not gonna use days, its just there to subtract it from the time
for (var i = 0; i < units.length; ++i) {
rv.push(Math.floor(diff / units[i]));
diff = diff % units[i];
}
//Get the year of this year
var thisFullYear = end.getFullYear();
//Check how many days there where in last month
var daysInLastMonth = new Date(thisFullYear, end.getMonth(), 0).getDate();
//Get this month
var thisMonth = end.getMonth();
//Subtract to get differense between years
thisFullYear = thisFullYear - start.getFullYear();
//Subtract to get differense between months
thisMonth = thisMonth - start.getMonth();
//If month is less than 0 it means that we are some moths before the start date in the year.
// So we subtract one year, and add the negative number (month) to 12. (12 + -1 = 11)
subAddDays = daysInLastMonth - start.getDate();
thisDay = end.getDate();
thisMonth = thisMonth - 1;
if(thisMonth < 0){
thisFullYear = thisFullYear - 1;
thisMonth = 12 + thisMonth;
//Get ends day of the month
}
//Subtract the start date from the number of days in the last month, add add the result to todays day of the month
subAddDays = daysInLastMonth - start.getDate();
subAddDays = thisDay + subAddDays;
if(subAddDays >= daysInLastMonth){
subAddDays = subAddDays - daysInLastMonth;
thisMonth++;
if (thisMonth > 11){
thisFullYear++;
thisMonth = 0;
}
}
return {
years: thisFullYear,
months: thisMonth,
days: subAddDays,
hours: rv[1],
minutes: rv[2],
seconds: rv[3]
};
}
//The start date/From date. Here i add one hour to offset it.
//var start = new Date(1814, 3, 20, 1);
//The end date. today, now!
//var end = new Date();
//Get the difference
//var d = timeDiff(start, end);
// Log that bitch
//console.log('years: '+ d.years + '. months: '+ d.months + '. days: ' + d.days + '. hours:' +d.hours+ '. minutes:' + d.minutes + '. seconds: ' + d.seconds);