In this tutorial we will learn how to Get Date Difference in Hours using JavaScript. To calculate the exact number of Hours between two dates we can use JavaScript new Date() constructor, Math.abs() method and Math.ceil() method.
Table of Contents
JavaScript new Date() Constructor
JavaScript new Date() Constructor creates a date object which represents current date and time.
The new Date() Constructor returns the date object which has current time in milliseconds from 1st January 1970 UTC till current date.
JavaScript Math.abs() method
JavaScript Math.abs() method is used to get the absolute value of the number.
JavaScript Math.ceil() method
JavaScript Math.ceil() method rounds up the number to the very next integer.
HTML Code
HTML Code is given below, in this code we have used input date elements to get two dates from user while a Button tag is used to execute a JavaScript function which will calculate date difference in Hours.
<input type="date" id="day1">
<input type="date" id="day2">
<button onclick="calculateHours()">Get Difference</button>
<p id="output"></p>
JavaScript Code
Take a look at the JavaScript code, getElementById() method is used to read the date from both input date elements. new Date constructor is used to get the date object in string format. Math.abs is used to get the absolute value of difference of two dates while Math.ceil is used to get exact date difference in Hours.
<script>
function calculateHours() {
var day1 = document.getElementById("day1").value;
var day2 = document.getElementById("day2").value;
const dateOne = new Date(day1);
const dateTwo = new Date(day2);
const time = Math.abs(dateTwo - dateOne);
const Hours = Math.ceil(time / (1000 * 60 * 60));
document.getElementById("output").innerHTML=Hours + ' Hours';
}
</script>
Demo
Video Tutorial
Watch video tutorial on Calculate Hours between two dates using JavaScript.