0

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
Daft
  • 10,277
  • 15
  • 63
  • 105
  • The documentation seems to indicate the use of [`from()`](http://momentjs.com/docs/#/displaying/from/)... – Heretic Monkey Sep 01 '16 at 14:27
  • Possible duplicate of [How to get difference between 2 Dates in Years, Months and days using moment.js](http://stackoverflow.com/questions/26063882/how-to-get-difference-between-2-dates-in-years-months-and-days-using-moment-js) – Heretic Monkey Sep 01 '16 at 14:30
  • @MikeMcCaughan the acepted answer for that question requires an additonal plugin. Which I cannot use. – Daft Sep 01 '16 at 14:39
  • The [edit] your question indicating that restriction. I couldn't possibly know that from the existing question. – Heretic Monkey Sep 01 '16 at 14:43
  • You can simply concat the strings right if you want response in a specific format?? Why do you wanna use another helper library when its so simple, why to complicate. :) – Prerna Jain Sep 01 '16 at 14:57
  • @PrernaJain If I concat the strings, I will get `2 years, 14 months`. Which is no good. I need `2 years, 2 months`. – Daft Sep 01 '16 at 15:01
  • 1
    okay.. I misunderstood then, apologies. – Prerna Jain Sep 01 '16 at 16:09

2 Answers2

1

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.

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
0

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