I want to find difference between two dates. I have tried this code but it gives me wrong values. I want get total minutes between two dates, so I am converting hours to minutes and adding to minutes.
var hourDiff = timeEnd - timeStart;
var diffHrs = Math.round((hourDiff % 86400000) / 3600000);
var diffMins = Math.round(((hourDiff % 86400000) % 3600000) / 60000);
diffMins = diffMins + (diffHrs * 60);
Here timeEnd
is Mon Jan 01 2007 11:30:00 GMT+0530 (India Standard Time)
,
and timeStart
is Mon Jan 01 2007 11:00:00 GMT+0530 (India Standard Time)
.
Here if hours difference I am getting 1
, it should be 0
and minutes I am getting 30
that is right. But hours should be 0
. Am I doing something wrong here?
Conclusion. We can get the difference between 2 dates in minutes by converting to timestamps in milliseconds, subtract the 2 timestamps, and convert the difference to minutes.
To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.
let x = new Date(); let y = new Date(); let dif = Math. abs(x - y) / 1000; Here, we find the number of seconds between two dates – x and y. We take the absolute difference between these two dates using the Math.
Try this code (uses ms as initial units)
var timeStart = new Date("Mon Jan 01 2007 11:00:00 GMT+0530").getTime();
var timeEnd = new Date("Mon Jan 01 2007 11:30:00 GMT+0530").getTime();
var hourDiff = timeEnd - timeStart; //in ms
var secDiff = hourDiff / 1000; //in s
var minDiff = hourDiff / 60 / 1000; //in minutes
var hDiff = hourDiff / 3600 / 1000; //in hours
var humanReadable = {};
humanReadable.hours = Math.floor(hDiff);
humanReadable.minutes = minDiff - 60 * humanReadable.hours;
console.log(humanReadable); //{hours: 0, minutes: 30}
JSFiddle: http://jsfiddle.net/n2WgW/
Try:
var diffHrs = Math.floor((hourDiff % 86400000) / 3600000);
Math.round
rounded the 0.5
hour difference up to 1
. You only want to get the "full" hours in your hours variable, do you remove all the minutes from the variable with the Math.floor()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With