Seb-Eisdrache
Seb-Eisdrache

Reputation: 13

JavaScript date timezone strange behavior

when I build a date form this ISO String "2016-02-01T16:00:00Z" I got Mon Feb 01 2016 17:00:00 GMT+0100

It seams that js is adding a hour for some reasons.

I think its a Timezone thing... but how can I fix this?

just do

var date = new Date('2016-02-01T16:00:00Z');
alert(date);

Upvotes: 0

Views: 202

Answers (3)

yavor.makc
yavor.makc

Reputation: 87

You need take into consideration the TimeZoneOffset Date.getTimezoneOffset() to show same date in different time zones. For example get offset in minutes convert to hours and add it to you time, or write function to convert date with depend time zone offset Like here

Upvotes: 0

jszobody
jszobody

Reputation: 28959

Javascript takes your datetime string, parses it in the timezone indicated (UTC), but then displays it in your current timezone.

When I run your code snippet, I get GMT-05:00 (EST).

So it's not adding an hour. It's just outputting the date in your local timezone.

Upvotes: 1

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19130

According to specifications, the ISO date string is parsed as UTC+0000, which is indicated by the Z char at the end.

Z is the zone designator for the zero UTC offset

When you indicate a date time string for the Date() constructor, it's parsed in UTC.
The method Date.prototype.toString() is formatting the date according to your timezone, which may differ from UTC. Because of that you get this offset.

It's possible to indicate a custom timezone at the end of an ISO string with ±hh:mm:

var d = new Date('2016-02-01T16:00:00+01:00');
d.toString() // will print "Feb 01 2016 16:00:00 GMT+0100", if you're in GMT+01:00

Upvotes: 2

Related Questions