0

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.

Haq.H
  • 863
  • 7
  • 20
  • 47
  • There are [many questions on this already](https://stackoverflow.com/search?q=%5Bjavascript%5D+difference+in+dates+in+years%2C+months), with many moment.js based answers. – RobG Apr 03 '20 at 22:47

1 Answers1

0

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>
Dan Cantir
  • 2,915
  • 14
  • 24
  • This produces incorrect results. A start date of 2020-03-02 and end date of 2025-02-03 produces "4 years 11 months and 3 days.", which is wrong. It should be 4 years, 11 months and 1 day. It produces similarly incorrect results for other durations too. You can test against [this answer](https://stackoverflow.com/a/35520995/257182) to [*How to get the difference of two dates in mm-dd-hh format in Javascript*](https://stackoverflow.com/questions/35504942/how-to-get-the-difference-of-two-dates-in-mm-dd-hh-format-in-javascript). – RobG Apr 03 '20 at 23:26