简体   繁体   中英

Get difference between two dates with inputs of string

Want to get the difference between the two dates.

Input: Dec 2016 to Feb 2018 (string)

Expected Output: 1 year 2 months

is any optimized way to achieve this?

You can use the moment library, and it's duration function to get the same result you desire.

Here are the implementations for the above question:

 function dateDiff(d1, d2) { return moment.duration(Math.abs(moment(d1, 'MMM YYYY').diff(moment(d2, 'MMM YYYY')))) } let diffDuration = dateDiff('Dec 2016', 'Nov 2019') diffDuration var years = diffDuration.years(), months = diffDuration.months(); console.log(years + ' years ' + months + ' months');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/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