Home > Web Front-end > JS Tutorial > How Can I Accurately Calculate the Difference Between Two Dates in Years, Months, and Days Using JavaScript?

How Can I Accurately Calculate the Difference Between Two Dates in Years, Months, and Days Using JavaScript?

Linda Hamilton
Release: 2024-12-02 12:53:16
Original
926 people have browsed it

How Can I Accurately Calculate the Difference Between Two Dates in Years, Months, and Days Using JavaScript?

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
Copy after login

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.

The above is the detailed content of How Can I Accurately Calculate the Difference Between Two Dates in Years, Months, and Days Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template