Search code examples
javascriptdatephonegap

Why does new Date(dateString) return two different dates on different devices with exactly the same input?


Knowing that my timezone is GMT+2, consider the following code:

  • Running On a Selfy 4G phone:

    myDate = "2017-05-12T09:00:00";
    dateFoo = new Date(myDate); //  Fri May 12 2017 11:00:00 GMT+0200 (CEST)
    
  • Running on a Galaxy S7:

    myDate = "2017-05-12T09:00:00";
    dateFoo = new Date(myDate); //  Fri May 12 2017 09:00:00 GMT+0200 (CEST)
    

Why is there an inconsistency in the outputs and how would I go about solving it?

My question is different from other similar questions (such as Why does Date.parse give incorrect results?) because in my case I am using the exact same string and it's the devices that differ.


Solution

  • The initial problem was that Date.parse on one device took my local time as the time zone, whereas on the other device it took UTC.

    By appending a Z at the end of my initial dateString, I forced the date to always be considered as UTC no matter what the device, therefore achieving consistent results with Date.parse().

    In order to then get the date in my local time, I used the answer to this question: https://stackoverflow.com/a/1486612/1875581.