0

My code is like this :

<script type="text/javascript">
    var createDate = '2016-07-12 09:09:38';
    createDate = createDate.replace(" ", "T");
    createDate = new Date(createDate);
    console.log(createDate);
</script>

In Firefox : Date {Tue Jul 12 2016 09:09:38 GMT+0700 (SE Asia Standard Time)}

In Chrome : Tue Jul 12 2016 16:09:38 GMT+0700 (SE Asia Standard Time)

Why the results are different in chrome?

moses toh
  • 12,344
  • 71
  • 243
  • 443
  • 2
    refer: http://stackoverflow.com/questions/15109894/new-date-works-differently-in-chrome-and-firefox – Dhara Parmar Jul 12 '16 at 07:06
  • I'm still confused. I try : http://stackoverflow.com/questions/15109894/new-date-works-differently-in-chrome-and-firefox. It's not working – moses toh Jul 12 '16 at 07:16
  • I try : `createDate = "2016-07-12T09:09:38Z";`, the result `Date {Tue Jul 12 2016 16:09:38 GMT+0700 (SE Asia Standard Time)}`. It's wrong. Should : `Date {Tue Jul 12 2016 09:09:38 GMT+0700 (SE Asia Standard Time)}` – moses toh Jul 12 '16 at 07:18
  • I try : `createDate = "2016-07-12T09:09:38+07:00";` and it's working – moses toh Jul 12 '16 at 07:28
  • "2016-07-12T09:09:38Z" *is correctly* "Tue Jul 12 2016 16:09:38 GMT+0700 (SE Asia Standard Time)" - not sure what the issue is. "Z" means GMT time zone, which is clearly +7 hours on SE Asia - so 9am here (excl. summer time) is 4pm there. – freedomn-m Jul 12 '16 at 07:55

1 Answers1

0

You need to explicitly tell JavaScript that the date you are storing is currently in UTC (which is the same a GMT). You do this by appending Z, which stands for Zulu Time. If you don't specify it, it falls back to the browser's implementation of the format, which is inconsistent.

var createDate = '2016-07-12 09:09:38Z';
createDate = createDate.replace(" ", "T");
createDate = new Date(createDate);

When you log the variable to the Console, you may notice differences between the Date/Time shown still. It's important to note that the Date/Time is correct. Again, it relates to the browser's implementation of the formatting. You can confirm that the internal values are correct with:

console.log(createDate.toString())
console.log(createDate.toUTCString())

The toString() will return the Date/Time in the local Time Zone, and the toUTCString() will return it in UTC/GMT, which should match the value you created the object with.

Gideon Pyzer
  • 22,610
  • 7
  • 62
  • 68