How to get difference between 2 Dates in Years, Months and days using moment.js? For example the difference between 4/5/2014 & 2/22/2013 should be calculated as 1 Year, 1 Month and 14 Days.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
This worked for me. Verified with Age calculator.
Moment.js can't handle this scenario directly. It does allow you to take the difference between two moments, but the result is an elapsed duration of time in milliseconds. Moment does have a Duration object, but it defines a month as a fixed unit of 30 days - which we know is not always the case.
Fortunately, there is a plugin already created for moment called "Precise Range", which does the right thing. Looking at the source, it does something similar to torazaburo's answer - but it properly accounts for the number of days in the month to adjust.
After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:
The output is "1 year 1 month 14 days"
You hardly need moment.
This takes advantage of the fact that the
Date
constructor is smart about negative values. For instance, if the number of months is negative, it will take that into account and walk back the year.Your calculation is wrong--it's not 14 days, it's six remaining days in February and the first five days of April, so it's 11 days, as the computer correctly computes.
Second try
This might work better given @MattJohnson's comment: