Difference between two dates per minute, javascript hours

I want to find the difference between the two dates. I tried this code, but it gives me the wrong values. I want to get total minutes between two dates, so I convert hours to minutes and add 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 - Mon Jan 01 2007 11:00:00 GMT+0530 (India Standard Time) .

Here, if the difference in hours I get 1 , it should be 0 and the minutes I get 30 , that's right. But the clock must be 0 . Am I something wrong here?

+6
source share
5 answers

Try:

 var diffHrs = Math.floor((hourDiff % 86400000) / 3600000); 

Math.round rounded the hourly difference of 0.5 to 1 . You only want to get the β€œfull” hours in the variable hours, you remove all minutes from the variable using Math.floor()

+3
source

Try this code (uses ms as starting 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/

+20
source

Try the following:

 var startDate = new Date('Jan 01 2007 11:00:00'); var endDate = new Date('Jan 01 2007 11:30:00'); var starthour = parseInt(startDate.getHours()); var endhour = parseInt(endDate.getHours()); if(starthour>endhour){ alert('Hours diff:' + parseInt(starthour-endhour)); } else{ alert('Hours diff:' + parseInt(endhour-starthour)); } 

And here is the working fiddle .

+4
source

If you are sure that the difference will be less than 24 hours, the following will be done.

 var timeStart= new Date('2015-01-01 03:45:45.890'); var timeEnd = new Date('2015-01-01 05:12:34.567'); var timeDiff = new Date(timeEnd.getTime() - timeStart.getTime()); var humanTime = timeDiff.toISOString().substring(11, 23); var diffHours = timeDiff.toISOString().substring(11, 12); 

humanTime - 01: 26: 48.677, diffHours - 01

0
source
 var timeDiff = function (date1, date2) { var a = new Date(date1).getTime(), b = new Date(date2).getTime(), diff = {}; diff.milliseconds = a > b ? a % b : b % a; diff.seconds = diff.milliseconds / 1000; diff.minutes = diff.seconds / 60; diff.hours = diff.minutes / 60; diff.days = diff.hours / 24; diff.weeks = diff.days / 7; return diff; } 
0
source

All Articles