I struggled with this exact problem for several days. Finally did something that I think is working. Looks like shit now, sloppy comments and stupid variable names, and I'll do the cleanup tomorrow. But I decided that I would publish it anyway if necessary.
EDIT: I cleared the code and made its essence. Have a look here: https://gist.github.com/4705863
EDIT2: Damn it, found a mistake. I'm on it. Bug fixed, now works great!
// 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);
source share