Skip to content

How to get total number of hours between two dates in javascript?

I am in a situation where I need to find out the total hour difference between two date objects but the thing is dates aren’t present in the actual format.

Date 1: 6 Apr, 2015 14:45
Date 2: 7 May, 2015 02:45

If it would have been in standard format, simply I would have been used below method: var hours = Math.abs(date1 - date2) / 36e5;

I am not sure how do I get the hour difference here… please help.

Answer

You can create date objects out of your strings:

const dateOne = "6 Apr, 2015 14:45";
const dateTwo = "7 May, 2015 02:45";
const dateOneObj = new Date(dateOne);
const dateTwoObj = new Date(dateTwo);
const milliseconds = Math.abs(dateTwoObj - dateOneObj);
const hours = milliseconds / 36e5;

console.log(hours);