Tuesday 30 September 2014

How to count month and days between two dates through JavaScript?

if (firstDate.getTime() > secondDate.getTime()) {
    var tmp = firstDate;
    firstDate = secondDate;
    secondDate = tmp;
}

var years = secondDate.getFullYear() - firstDate.getFullYear();
var months = secondDate.getMonth() - firstDate.getMonth();
var days = secondDate.getDate() - firstDate.getDate();

for (var i = 0; days < 0; ++i) {
    // while the day difference is negative
    // we break up months into days, starting with the first
    months -= 1;
    days += new Date(
        firstDate.getFullYear(),
        firstDate.getMonth() + 1 + i,
        0, 0, 0, 0, 0
    ).getDate();
}
for (; months < 0;) {
    years -= 1;
    months += 12;
}
console.log((12 * years + months) + ' months and ' + days + ' days');
Examples:
02/12 to 02/22: 10 days
09/27 to 11/01: 4 days, 1 month
12/31 to 03/01: 1 day, 2 months
05/31 to 06/30: 30 days
01/31 to 03/30: 30 days, 1 month
10/27/2010 to 08/26/2014: 30 days, 45 months
if (firstDate.getTime() > secondDate.getTime()) {
   var tmp = firstDate;
   firstDate = secondDate;
   secondDate = tmp;
}
var years = secondDate.getFullYear() - firstDate.getFullYear();
var months = secondDate.getMonth() - firstDate.getMonth();
var days = secondDate.getDate() - firstDate.getDate();
for (var i = 0; days < 0; ++i) {
    // while the day difference is negative
    // we break up months into days, starting with the first
    months -= 1;
    days += new Date(
        firstDate.getFullYear(),
        firstDate.getMonth() + 1,
        0, 0, 0, 0, 0
    ).getDate();
}
for (; months < 0;) {
    years -= 1;
    months += 12;
}
console.log((12 * years + months) + ' months and ' + days + ' days');
Examples:
02/12 to 02/22: 11 days 
09/27 to 11/01: 5 days, 1 month 
12/31 to 03/01: 2 day, 2 months 
05/31 to 06/30: 31 days 
01/31 to 03/30: 31 days, 1 month 
10/27/2010 to 08/26/2014: 31 days, 45 months