I'm looking for a way to use momentjs to parse two dates, to show the difference.
I want to have it on the format: "X years, Y months, Z days".
For the years and months the moment library and modulo operator works nice. But for the days it's another tale as I don't want to handle leap years and all that by myself. So far the logic I have in my head is this:
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'years');
var months = a.diff(b, 'months') % 12;
var days = a.diff(b, 'days');
// Abit stuck here as leap years, and difference in number of days in months.
// And a.diff(b, 'days') returns total number of days.
return years + '' + months + '' + days;
From the docs, since 2.0. 0, moment#diff will return number rounded down, so you only need to : age = moment(). diff(birthDate, 'years') .
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD"). fromNow(). This will calculate the difference between today and your provided date.
To get the number of year between 2 dates, use the getFullYear() method to get the year of the date objects and subtract the start date from the end date. The getFullYear method returns an integer that represents the year of the given date. Copied! function getYearDiff(date1, date2) { return Math.
You could get the difference in years and add that to the initial date; then get the difference in months and add that to the initial date again.
In doing so, you can now easily get the difference in days and avoid using the modulo operator as well.
Example Here
var a = moment([2015, 11, 29]); var b = moment([2007, 06, 27]); var years = a.diff(b, 'year'); b.add(years, 'years'); var months = a.diff(b, 'months'); b.add(months, 'months'); var days = a.diff(b, 'days'); console.log(years + ' years ' + months + ' months ' + days + ' days'); // 8 years 5 months 2 days
I'm not aware of a better, built-in way to achieve this, but this method seems to work well.
Moment.js also has duration
object. A moment is defined as single point in time, whereas duration is defined as a length of time which is basically what you want.
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var diffDuration = moment.duration(a.diff(b));
console.log(diffDuration.years()); // 8 years
console.log(diffDuration.months()); // 5 months
console.log(diffDuration.days()); // 2 days
What @Josh suggest may work, but is definitely not the right way of calculating difference in 2 moments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With