Wednesday, March 23, 2016

JavaScript DateDiff

Earlier I blogged about creating a DateDiff function in JavaScript that returns calendar difference between two dates. It returns the Year, Months and Days difference between two dates. Here is the link for my previous blog


I enhanced that DateDiff function to return additional details such as Hours, Minutes and Seconds. Here is the updated code

function dateDiff(startdate, enddate) {
    //define moments for the startdate and enddate
    var startdateMoment = moment(startdate);
    var enddateMoment = moment(enddate);

    if (startdateMoment.isValid() === true && enddateMoment.isValid() === true) {
        //getting the difference in years
        var years = enddateMoment.diff(startdateMoment, 'years');

        //to calculate the months, first get the previous year and then subtract it
        startdateMoment.add(years, 'years')
        var months = enddateMoment.diff(startdateMoment, 'months')

        //to calculate the days, first get the previous month and then subtract it
        startdateMoment.add(months, 'months');
        var days = enddateMoment.diff(startdateMoment, 'days')

        //Similar to days go the previous day
        startdateMoment.add(days, 'days')
        var hours = enddateMoment.diff(startdateMoment, 'hours')

        //Getting minutes
        startdateMoment.add(hours, 'hours')
        var minutes = enddateMoment.diff(startdateMoment, 'minutes')

        //Similar to days go the previous day
        startdateMoment.add(minutes, 'minutes')
        var seconds = enddateMoment.diff(startdateMoment, 'seconds')

        return {
            years: years,
            months: months,
            days: days,
            hours: hours,
            minutes: minutes,
            seconds: seconds
        };

    }
    else {
        return undefined;
    }
}

Plunker for this DateDiff function

No comments:

Post a Comment