3

This one has stumped me. It should be so simple I would think. I am doing some very simple date subtraction in Javascript. I am subtracting the same dates and I would think it would give zero hours, but it gives 18 hours.

let inDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime();
let outDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime();

document.getElementById('date').innerHTML = new Date(outDate - inDate);
<div id='date'>

</div>

In case it produces different results based on where you are, the result I am getting is this:

Wed Dec 31 1969 18:00:00 GMT-0600 (Central Standard Time)

dmikester1
  • 1,374
  • 11
  • 55
  • 113
  • 3
    `outDate - inDate` results in `0` wherever you are, but `new Date(0)` prints differently depending on the timezone you’re in. – Lennholm Aug 27 '19 at 20:05

1 Answers1

4

This is due to your timezone. If you convert to GMT String before print it the time will be correct. (Jan 01, 1969 00:00:00)

 new Date(outDate - inDate).toGMTString()

You should see the correct date.

let inDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime()
let outDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime()

console.log(new Date(inDate - outDate).toGMTString())
Dupocas
  • 20,285
  • 6
  • 38
  • 56
  • Thanks! I figured it was something super simple like that! :) – dmikester1 Aug 27 '19 at 20:03
  • Was a typo. It's supposed to be `GMT String` instead of `UTC` – Dupocas Aug 27 '19 at 20:16
  • My browser, in the time zone shown, gave 21:00 hours as the time, like this: Wed Dec 31 1969 21:00:00 GMT-0300 (Uruguay Standard Time) So, I'm in the day before, three hours short of the epic. Interesting. Thank you. – Douglas Lovell Aug 27 '19 at 20:40
  • @Dupocas looks like that function is deprecated. toUTCString is working great for me. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString – dmikester1 Aug 27 '19 at 20:47
  • Why is my result `Thu, 01 Jan 1970 00:00:00 GMT` ? – deblocker Aug 27 '19 at 21:27
  • @deblocker for this answer, that is the desired and expected result – dmikester1 Aug 27 '19 at 21:41
  • 2
    @deblocker subtracting 2 identical dates produces a zero date which is equal to the Epoch date: https://stackoverflow.com/questions/2533563/why-are-dates-calculated-from-january-1st-1970/2533567 – dmikester1 Aug 27 '19 at 21:46