-1

I have two dates in Javascript-

  1. In the format 16-Feb-2016.
  2. In the format 26-01-2015.

Now i have to get the difference of both the dates using javascript in years and months.

I am not getting how to do it because both the dates are in different format.

rusty bit
  • 371
  • 2
  • 17
  • There are many questions and answers here about parsing dates, the formats in the OP require about 3 lines of code. Getting the difference in years and months is not trivial, I don't think Moment.js does that accurately. Have a look at the answer [*here*](http://stackoverflow.com/questions/35504942/how-to-get-the-difference-of-two-dates-in-mm-dd-hh-format-in-javascript/35520995#35520995) (which includes a parser that can easily be modified to suit the formats here). – RobG Feb 23 '16 at 22:43

1 Answers1

1

Paste the following code in console and check. Hope it helps.

    var d1 = "16-Feb-2016";
    var d2 = "26-01-2015";
    var date1 = new Date(d1);
    // The date to be formatted in mm-dd-yy
    var date2 = (d2).split("-");
    date2 = date2[1] + "-" + date2[0] + "-" + date2[2];
    date2 = new Date(date2);

    function getDiff(date1, date2) {
    var monthDiff= (date1.getFullYear()*12)+(date1.getMonth()+1)-(date2.getFullYear()*12)-(date2.getMonth()+1);
    var diffYear = parseInt(monthDiff/12);
    var diffMonth = monthDiff%12;
    return (diffYear + " years, " + diffMonth + " month");
    }

    var difference = getDiff(date1, date2);
    console.log(difference);
abhiagNitk
  • 1,047
  • 10
  • 19