私はこの正確な問題に数日間苦労しています。最後に、私がうまくいくと思うものを作りました。今はくだらない、ずさんなコメントとばかげた変数名のように見えます。明日はクリーンアップを行います。しかし、必要な場合に備えて、とにかく投稿すると思いました。
編集:コードをクリーンアップし、その要点を作成しました。ここで確認してください: https://gist.github.com/4705863
EDIT2:くそー、バグが見つかりました。やってる。バグが修正され、正常に動作するようになりました!
// 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);