Recently I got a requirement to find the difference between
two dates. I want to result as the number of years, months and days between the
two dates. Further I am interested in the calendar difference that considers
months with 28, 29, 30 and 31 days. For example the difference between Jan 28th,
2015 and Mar 29th, 2015 is 0 years, 2 months and 1 day.
Obviously there is no out of box function and I could not
find a simple library that does what I need. In c# and other server side languages
this functionality is already available.
I wrote a small function which calculates the difference
between two dates. To simplify my calculations I used moment.js. As you know
moment.js is a very good date library
Here is my function which returns the DateDiff between two
dates:
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');
//moment
returns the total months between the two dates, subtracting the years
var months = enddateMoment.diff(startdateMoment, 'months') - (years * 12);
//to
calculate the days, first get the previous month and then subtract it
startdateMoment.add(years, 'years').add(months, 'months');
var days = enddateMoment.diff(startdateMoment, 'days')
return { years: years, months: months, days: days };
}
}
The output of the function is a javascript object containing
years, months and days elapsed between the two dates
Here is the Plunker for this
http://plnkr.co/edit/YovdOb?p=preview
Update: I enhanced this function to include Hours, Minutes and Seconds. Please see my updated blog on this
http://www.spaprogrammer.com/2016/03/javascript-datediff.html
http://plnkr.co/edit/YovdOb?p=preview
Update: I enhanced this function to include Hours, Minutes and Seconds. Please see my updated blog on this
http://www.spaprogrammer.com/2016/03/javascript-datediff.html