Determining Date Differences in Years, Months, and Days in JavaScript
Determining the difference between two dates in years, months, and days can be challenging in JavaScript due to inconsistencies in solutions that only provide differences in one unit (years, months, or days) or inaccuracies in calculations.
Here's a more comprehensive solution that takes into account common and leap years as well as the exact difference in days between months:
today = new Date(); past = new Date(2010, 05, 01); // Equivalent to June 1, 2010 function calcDate(date1, date2) { // Calculate the difference in milliseconds var diff = Math.floor(date1.getTime() - date2.getTime()); // Convert milliseconds to days var day = 1000 * 60 * 60 * 24; var days = Math.floor(diff / day); // Calculate months and years from days var months = Math.floor(days / 31); var years = Math.floor(months / 12); // Format the message var message = date2.toDateString(); message = " was "; message = days " days "; message = months " months "; message = years " years ago \n"; return message; } console.log(calcDate(today, past)); // Output: Tue Jun 01 2010 was 1143 days 36 months 3 years ago
This solution accurately calculates the difference between two dates by converting the difference in milliseconds to days, and then further deriving the months and years from the total days.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3