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


  1. JavaScript is the language future. The new JavaScript Version (Ecmascript 6) has been released.

    JavaScript Online Training

    Javascript Online Training

  2. JavaScript is the language future. The new JavaScript Version (Ecmascript 6) has been released.

    Javascript Online Training | Angularjs Online Training

  3. Advertising is your main tool to have the business ready to go. Actually, everybody is busy in their company marketing over the World Wide Web. Unfortunately, online company is scammed with scammers. On occasion the provider hires you freelance, or occasionally it is a site designer which orders the copy google At an identical time, if you decide on the most suitable company having excellent reviews and reputation, you will enjoy well composed works.

  4. Gosh why I did ever choose this course to be finished? I can't get all that progamming thing even a bit. Really, just let me do what I can do. I need someone to write my essay for me every time our teacher gives us homework. I've spend tons of money already. I want to die.