5

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.

Test Email
  • 135
  • 1
  • 4
  • 8
  • i would recommend you to take a look at [momentjs](http://momentjs.com/) – PhilSchneider Apr 13 '15 at 07:42
  • 4
    Couldn't you convert both time stamps to seconds, subtract one from the other, then divide by 60 and 60 again? – Gary Hayes Apr 13 '15 at 07:42
  • What do you mean by actual format? Regardless, moment.js can probably handle your problem. – doldt Apr 13 '15 at 07:42
  • possible duplicate of [How to get the hours difference between two date objects?](http://stackoverflow.com/questions/19225414/how-to-get-the-hours-difference-between-two-date-objects) – Code Lღver Apr 13 '15 at 07:50

4 Answers4

12

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);
Timur Osadchiy
  • 5,699
  • 2
  • 26
  • 28
5

You can create two date objects from the strings you have provided

var date1 = new Date("6 Apr, 2015 14:45");
var date2 = new Date("7 May, 2015 02:45");

then you can simply get the timestamp of the two dates and find the difference

var difference = Math.abs(date1.getTime() - date2.getTime());

Now to convert that to hours simply convert it first to seconds (by dividing by 1000 because the result is in milliseconds), then divid it by 3600 (to convert it from seconds to hours)

var hourDifference = difference  / 1000 / 3600;
leopik
  • 2,323
  • 2
  • 17
  • 29
0
var date1 = new Date("6 Apr, 2015 14:45").getTime() / 1000;

var date2 = new Date("7 May, 2015 02:45").getTime() / 1000;

var difference = (date2 - date1)/60/60;
console.log(difference); //732 hours or 30.5 days
Gary Hayes
  • 1,728
  • 1
  • 15
  • 23
0

I'm not sure what you mean, but this works for me.

<!DOCTYPE html>
<html>
<body>

<p id="hours"></p>

<script>
var d1 = new Date("1 May, 2015 14:45");
var d2 = new Date("29 April, 2015 14:45");
var hours = (d1-d2)/36e5;
document.getElementById("hours").innerHTML = hours;
</script>

</body>
</html>
user1991275
  • 100
  • 1
  • 1
  • 5