Krypton Krypton - 3 months ago 8
Javascript Question

Counting down days left to a date?

I'm having trouble using a function with JS.
I got this JS code from here Difference between two dates in years, months, days in JavaScript

The months work fine but when I try to call the days it doesn't seem to work right, it will show 30 days when it should be 24. can anyone see anything wrong with the code?

function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function daysInMonth(date) {
return new Date(date.getYear(), date.getMonth() + 1, 0).getDate();
}
function diffDate(date1, date2) {
if (date2 && date2.getTime() && !isNaN(date2.getTime())) {
var months = monthDiff(d1, d2);
var days = 0;

if (date1.getUTCDate() >= date2.getUTCDate()) {
days = date1.getUTCDate() - date2.getUTCDate();
}
else {
months--;
days = date1.getUTCDate() - date2.getUTCDate() + daysInMonth(date2);
}

// Use the variables months and days how you need them.
}
}


Here's the var that uses the functions

var months = monthDiff(new Date(), options.timestamp ) % 12 + 1,
days = daysInMonth(new Date()),

Answer

Here is a function that will return the difference expressed in number of years, months and days:

function dateDiff(d1, d2) {
    var years = 0, months = 0, days = 0, arr;
    if (d1 > d2) { // call inverse
        interval = dateDiff(d2, d1);
        return {
            years: -interval.years, 
            months: -interval.months, 
            days: -interval.days
        };
    }
    days = d2.getDate() - d1.getDate();
    if (days < 0) {
        months--;
        days+= new Date(new Date(d2).setDate(0)).getDate();
    }
    months += d2.getMonth() - d1.getMonth();
    if (months < 0) {
        years--;
        months+=12;
    }
    years += d2.getFullYear() - d1.getFullYear();
    return {
        years: years, 
        months: months,
        days: days
    };
}

// Sample data
var d1 = new Date('2013-10-20');
var d2 = new Date('2016-12-16')
// Call
var interval = dateDiff(d1, d2);
// Output each number separately
console.log('Years: ', interval.years);
console.log('Months: ', interval.months);
console.log('Days: ', interval.days);