-1

A really long title, I know, but I had to highlight the fact, that I'm confronting a situation that's a little different than all the usual javascript date conversions.

I am getting the following datetime in a string from the server:

2017-05-18T08:00:00

When I put this string into the following statement:

var newDate = new Date("2017-05-18T08:00:00");

It assumes it's in the UTC timezone, so it automatically adjusts, and converts it into local time, which in Sidney would become 2017/05/18 18:00:00.

Any way that I can stop the date constructor to assume that the string is UTC time (make it assume that it's local time)?

Laureant
  • 979
  • 3
  • 18
  • 47
  • can you append -10:00 to the end? – epascarello May 18 '17 at 12:12
  • This question is covered in many different places [here](http://stackoverflow.com/questions/18181524/how-do-you-preserve-a-javascript-dates-time-zone-from-browser-to-server-and-ba), [here](http://stackoverflow.com/questions/2771609/how-to-ignore-users-time-zone-and-force-date-use-specific-time-zone?noredirect=1&lq=1) and [here](http://stackoverflow.com/questions/31127544/stop-javascript-datetime-adjusting-to-local-time-zone?rq=1) to name a few – Sandman May 18 '17 at 12:15
  • Any chance you can fix the server so it gives you the ISO 8601 string with time zone? It's an anti-pattern to expect consumers to know where the server is located. – Alfredo Delgado May 18 '17 at 12:15
  • "2017-05-18T08:00:00" should be parsed as local, not UTC, so there's one example of why you shouldn't use the built-in parser. See [*Why does Date.parse give incorrect results?*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results?s=1|7.9852). – RobG May 19 '17 at 05:11

2 Answers2

1

use getTimezoneOffset() function to adjust timezone. By default Date converts it to local timezone :(

  • Thanks. Using it like this works: new Date(new Date(timestampStr).getTime() + (new Date().getTimezoneOffset() * 60 * 1000)) – Laureant May 18 '17 at 12:26
  • This is a bad idea. The OP behaviour is not standards compliant, so adjusting by the timezone offset will mean the result is wrong in standards compliant hosts (which is quite a few). – RobG May 19 '17 at 05:15
0

If you're applying your code in serious applications, consider a tool like Moment.js

Sventies
  • 2,314
  • 1
  • 28
  • 44