Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two dates in minute, hours javascript

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?

like image 679
sp_m Avatar asked Dec 30 '13 12:12

sp_m


People also ask

How do you find the difference between two dates and minutes?

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.

How do you find the difference between two dates in hours?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.

How do I get the difference between two dates and seconds in Javascript?

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.


2 Answers

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/

like image 66
strah Avatar answered Sep 23 '22 10:09

strah


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

like image 39
Cerbrus Avatar answered Sep 26 '22 10:09

Cerbrus