-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
27 lines (23 loc) · 1.17 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//Declaring and initializing variables
let submit = document.getElementById("submit");
let output = document.getElementById("output");
submit.addEventListener("click", () => {
//Create a Date object from input value
let date1 = new Date(document.getElementById("date-1").value);
let date2 = new Date(document.getElementById("date-2").value);
//Check if the input dates are valid
//If valid calculate the difference
if (date1.getTime() && date2.getTime()) {
//Calculate difference in time using getTime function
//getTime calculates number of years since January 1,1970
let timeDifference = date2.getTime() - date1.getTime();
//Since this value is in milliseconds we need to convert it into days
//We want the difference to be a non-negative number. Hence we use Math.abs()
let dayDifference = (Math.abs(timeDifference / (1000 * 3600 * 24))) - 1;
output.innerHTML = `<span>${dayDifference}</span> days between both the dates`;
}
//Else display that the input is valid
else {
output.innerHTML = "Please select a valid date";
}
});