0

I'm trying to calculate the difference betweent two times, like 10:54 and 09:00 (expected difference is 1 hour 54 minutes):

Date.prototype.diffTime = function(date){
    return new Date(this-date);
}

But this returns one hour more than I expect:

Thu Jan 01 1970 10:54:00 GMT+0100 (CET)
Thu Jan 01 1970 09:00:00 GMT+0100 (CET)
Thu Jan 01 1970 02:54:00 GMT+0100 (CET)

So why does it add one hour? The input times are correct. When I use getTime(), I get 1.9 hours (this-date/1000/60/60), which is also correct.

Thank you for your comments. I now wrote a simpler function which does what I need:

function getTimeHHMI(date){
    var minutes = date/1000/60;
    var hours = Math.floor(minutes/60);
    minutes -= hours*60;

    return [hours, minutes].join(':'); // returns 1:54
}
Kugel
  • 808
  • 8
  • 26

2 Answers2

2

When you pass this-date to new Date, the value is interpreted as a unix timestamp representing 1:54am. 1:54am in GMT+0 is the same as 2:54am in GMT+1. I.e. the browser converts the unix timestamp to your local time.

Converting the duration to a date value doesn't make sense, since duration is independent of time zones.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

this-date returns milliseconds .If you construct date from the difference , it would be date way long 1970

Date.prototype.diffTime = function(date){
    return (this-date)/1000/60/60;
}
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21