In this tutorial we will see how to calculate Date Difference in Days using JavaScript. For this we have used new Date() constructor along with Math.abs() and Math.ceil() JavaScript methods.
Table of Contents
HTML Code
HTML Code is given below, This code contains two input date type HTML elements, one button and one paragraph element, to display the result of days calculation.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Date Difference in Days</title>
</head>
<body>
<input type="date" id="d1">
<input type="date" id="d2">
<button onclick="calculateDays()">Get Difference</button>
<p id="output"></p>
</body>
</html>
onclick event
The onclick event occurs when an HTML element is clicked. In this example onclick event handler is used to execute the JavaScript function "calculateDays()", on a click of button tag.
This JavaScript function will calculate the difference between two dates.
JavaScript Code
Take a look at the JavaScript code, this code is further explained below.
<script>
function calculateDays() {
var d1 = document.getElementById("d1").value;
var d2 = document.getElementById("d2").value;
const dateOne = new Date(d1);
const dateTwo = new Date(d2);
const time = Math.abs(dateTwo - dateOne);
const days = Math.ceil(time / (1000 * 60 * 60 * 24));
document.getElementById("output").innerHTML=days;
}
</script>
Demo
getElementById() method
getElementById() method is used to target or select the HTML element. In this example it is used to read the dates of input elements and to display the output with the help of paragraph tag.
JavaScript Date Object
Date object is created with the new Date() constructor. Two dates from two different input elements are passed to new Date() constructor which converts them to a full text string format.
Math.abs()
The Math.abs() function returns the absolute value of a number, it is used in this example to avoid the negative numbers, in case if the second date is something which comes before the first one in calendar.
Math.ceil()
The Math.ceil() function rounds a number up to the next largest integer.
The value stored in time variable is in milliseconds, so it is divided by "1000 * 60 * 60 * 24", which is total number of milliseconds (86400000) in a day, this is done to get the answer in days.
Video Tutorial
Watch video tutorial on how to Find Date Difference in Days using JavaScript.