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

前端 未结 26 2469
执念已碎
执念已碎 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

       let startDate = moment(new Date('2017-05-12')); // yyyy-MM-dd
       let endDate = moment(new Date('2018-09-14')); // yyyy-MM-dd
    
       let Years = newDate.diff(date, 'years');
       let months = newDate.diff(date, 'months');
       let days = newDate.diff(date, 'days');
    
    console.log("Year: " + Years, ", Month: " months-(Years*12), ", Days: " days-(Years*365.25)-((365.25*(days- (Years*12)))/12));
    

    Above snippet will print: Year: 1, Month: 4, Days: 2

提交回复
热议问题