How to calculate years, months and days between two dates in javascript?

25-May-2023

.

Admin

How to calculate years, months and days between two dates in javascript?

In this short tutorial we will cover an Difference between two dates in years. This article will give you simple example of months. This article will give you simple example of days in JavaScript. I explained simply about How to calculate years and months between two dates in javascript. You just need to some step to done Get difference between 2 dates in JavaScript.

One way to calculate years, months, and days between two dates in JavaScript is to use the built-in Date object and some simple math. Here's an example function that takes in two dates as parameters and returns an object with the number of years, months, and days between them:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to calculate years, months and days between two dates in javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

function getDateDiff(startDate, endDate) {

// Convert both dates to milliseconds

var startDateMS = startDate.getTime();

var endDateMS = endDate.getTime();

// Calculate the difference in milliseconds

var diffMS = endDateMS - startDateMS;

// Convert back to days and round down

var diffDays = Math.floor(diffMS / (1000 * 60 * 60 * 24));

// Calculate years and remaining days

var years = Math.floor(diffDays / 365);

var remainingDays = diffDays % 365;

// Calculate months from remaining days

var months = Math.floor(remainingDays / 30);

//Calculate weeks from remaining days

var weeks=Math.floor(remainingDays/7);

//Calculate remaining Days

var remDays=remainingDays%7

// Return the result as an object

return {

years: years,

months: months,

weeks:weeks,

days:remDays

};

}

//To use this function, simply pass in two Date objects:

var startDate = new Date('2021-01-01');

var endDate = new Date('2022-05-31');

var dateDiff = getDateDiff(startDate, endDate);

console.log(dateDiff.years); // Output: 1

console.log(dateDiff.months); // Output:4

console.log(dateDiff.weeks); // Output :20

console.log(dateDiff.days); //Output:3

</script>

</html>

#JavaScript