Daft
Daft

Reputation: 10964

Can I get the difference between two dates in years and months with momentjs?

The following will give me years and months:

var years = toDate.diff(todaysDate, 'years');
var months = toDate.diff(todaysDate, 'months');

so if the difference is 2 years and 2 months, I will get:

2
14

Can I use moment to get get the differece in this format?

2 years, 2 months

Upvotes: 0

Views: 5106

Answers (2)

VincenzoC
VincenzoC

Reputation: 31482

Since you don't want to add additional plug-in you can use modulus operator % to convert months to correct value.

Here a working example:

var todaysDate = moment();
var toDate = moment().add(14, 'months');

var years = toDate.diff(todaysDate, 'years');
var months = toDate.diff(todaysDate, 'months');

console.log(years + ' years, ' + months % 12 + ' months');
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Another solution using moment-duration-format is the following:

var todaysDate = moment();
var toDate = moment().add(14, 'months');

var months = toDate.diff(todaysDate, 'months');

var duration = moment.duration(months, 'months');
console.log(duration.format("y [years] M [months]"));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

In this way you create a duration object from months value and then you format it according your needs using the plug-in.

Upvotes: 1

ruhla.mates
ruhla.mates

Reputation: 21

Not for the time being. I know that they are working on a plugin for formatting duration, but don't count on that to be released any time soon.

https://github.com/moment/moment/issues/1048

Upvotes: 0

Related Questions