简体   繁体   中英

Convert the difference between 2 dates to 'y mo d' format using Moment.js

I am running into a wall trying to figure out how to convert the difference between two dates to an accurate breakdown of how many years, months and days it's been since the start date. The format I want to show is: '1y 5mo 2d' given two dateTimes that have that difference. I tried using Moment.js and it works pretty well for 'y' and 'mo' but I am running into a wall trying to figure out how to accurately get the number of days.

export const convertDaysToYMD = (dates: {start, end})=>{
  const start = Moment(dates.start)
  const end = Moment(dates.end)
  const y = end.diff(start, 'years')
  const m = end.diff(start, 'months')
  const d = end.diff(start, 'days')
  console.log('y', y + ' m', m%12 + ' d', d)
}

I can accuratly get the number of years and then the number of months by using mod(12) but due to the number of days changing per month I don't quite know how to get the number of days. Any help would be great.

You can use moment's duration method like this:

 const start = moment('2020-01-02'); const end = moment('2020-02-03'); const duration = moment.duration(end.diff(start)); console.log(`${duration.years()} years ${duration.months()} months and ${duration.days()} days.`)
 <script src="https://momentjs.com/downloads/moment.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM