Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  151] [ 3]  / answers: 1 / hits: 36497  / 9 Years ago, sun, november 29, 2015, 12:00:00

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;

More From » date

 Answers
52

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.


[#64232] Thursday, November 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mattieparisp

Total Points: 612
Total Questions: 109
Total Answers: 104

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;