Difference between two dates in minute, hours javascript

Viewed 53919

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?

8 Answers

You can Try This:-

function diff_hours(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60 * 60);         // For Hours
  //diff /= (60);          For Minutes
  return Math.abs(Math.round(diff));

 }

dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2));            // you will get '24' hours


dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 13, 2014 11:13:00");
console.log(diff_hours(dt1, dt2));           // you will get '3' hours

You can get Time Difference in hours and minutes format like below

const startTime = new Date(event.startTime);
const endTime = new Date(event.endTime);
const diff = endTime.getTime() - startTime.getTime();
const hrDiff = diff / 3600 / 1000; // 1.555555
const totalHours = parseFloat((hrDiff).toFixed(2)); // 1.5
Related