Skip to content Skip to sidebar Skip to footer

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:4

Solution 1:

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 = newDate(dateOne);
const dateTwoObj = newDate(dateTwo);
const milliseconds = Math.abs(dateTwoObj - dateOneObj);
const hours = milliseconds / 36e5;

console.log(hours);

Solution 2:

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

var date1 = newDate("6 Apr, 2015 14:45");
var date2 = newDate("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)

varhourDifference=difference/1000/3600;

Solution 3:

var date1 = newDate("6 Apr, 2015 14:45").getTime() / 1000;

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

var difference = (date2 - date1)/60/60;
console.log(difference); //732 hours or 30.5 days

Solution 4:

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

<!DOCTYPE html><html><body><pid="hours"></p><script>var d1 = newDate("1 May, 2015 14:45");
var d2 = newDate("29 April, 2015 14:45");
var hours = (d1-d2)/36e5;
document.getElementById("hours").innerHTML = hours;
</script></body></html>

Post a Comment for "How To Get Total Number Of Hours Between Two Dates In Javascript?"