Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 572
Test Email Avatar asked Apr 13 '15 07:04

Test Email


1 Answers

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);
like image 90
Timur Osadchiy Avatar answered Sep 27 '22 22:09

Timur Osadchiy