简体   繁体   中英

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.

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);

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;
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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM