Difference between two dates in minute, hours javascript

Try this:

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.


If you are confident that the difference will be less that 24 hours, the following works.

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 is 01:26:48.677, diffHours is 01


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


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/