How to get difference between 2 Dates in Years, Months and days using moment.js

前端 未结 3 863
长情又很酷
长情又很酷 2020-12-06 05:57

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

3条回答
  •  天涯浪人
    2020-12-06 06:38

    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:

    var m1 = moment('2/22/2013','M/D/YYYY');
    var m2 = moment('4/5/2014','M/D/YYYY');
    var diff = moment.preciseDiff(m1, m2);
    console.log(diff);
    

    The output is "1 year 1 month 14 days"

提交回复
热议问题