1

As I am new to javascript so I am asking this question how to find difference between two dates in hours.I am successfully calculated difference but when I give time in format of AM/PM it gives me output as NAN Please check my code I am posting below and thanks in advance:

function calculateTime() {
  var d2 = new Date('2018-02-12 03:00:00 AM');
  var d1 = new Date('2018-02-10 08:00:00 AM');
  var seconds =  (d2- d1)/1000;
  var hours = seconds/3600;
  console.log(hours);
}
calculateTime();
Fecosos
  • 944
  • 7
  • 17
user7596840
  • 137
  • 15

2 Answers2

2

Simply subtract the date objects from one another.

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is short for 60*60*1000 and so dividing by 36e5 will give you hours.

Joshua
  • 162
  • 1
  • 2
  • 9
1

Firefox will return Invalid date for the format YYYY-MM-DD HH:MM:SS AM

One option is to use year, month, day separately on new Date()

new Date(year, month [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

Like:

function calculateTime() {
  var formatDate = function(dt) {
    let n = dt.split(/\D/).splice(0,6);
    n[3] = dt.slice(-2) === 'PM' ? ( +n[3] + 12 ) : n[3]; //Update Hour
    n[1] = n[1] - 1; //Update month
    return n;
  }

  var d2 = new Date(...formatDate('2018-02-12 03:00:00 AM'));
  var d1 = new Date(...formatDate('2018-02-10 08:00:00 AM'));

  var seconds = (d2 - d1) / 1000;

  var hours = seconds / 3600;
  console.log(hours);
}

calculateTime();

Doc: new Date

Eddie
  • 26,593
  • 6
  • 36
  • 58