Difference between two dates in years, months, days in JavaScript

前端 未结 26 2475
执念已碎
执念已碎 2020-11-22 07:18

I\'ve been searching for 4 hours now, and have not found a solution to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 201

26条回答
  •  不思量自难忘°
    2020-11-22 08:01

    You should try using date-fns. Here's how I did it using intervalToDuration and formatDuration functions from date-fns.

    let startDate = Date.parse("2010-10-01 00:00:00 UTC");
    let endDate = Date.parse("2020-11-01 00:00:00 UTC");
    
    let duration = intervalToDuration({start: startDate, end: endDate});
    
    let durationInWords = formatDuration(duration, {format: ["years", "months", "days"]}); //output: 10 years 1 month
    

提交回复
热议问题