I am trying to display a date in javascript. I receive the date from backend like this: 2020-09-22T17:10:25Z
(from and Instant object in Java).
When I try to call new Date("2020-09-22T17:10:25Z")
I get: Tue Sep 22 2020 20:10:25 GMT 0300 (Eastern European Summer Time)
. The issue with this is that I am not in a GMT 0300
timezone but rather GMT 0200
.
When I try to call new Date()
on the other hand I get Thu Dec 08 2022 20:34:11 GMT 0200 (Eastern European Standard Time)
which is my correct timezone.
My question is, why in the first case I get the GMT 0300
and in the second case I get GMT 0200
? The Z
in the string I am trying to parse stands for Zulu
or zero hour offset
, so why does the 2 different approaches use different timezones?
CodePudding user response:
It looks like you are in GMT 2
in winter, but in summer (in September) you are in summer time which is GMT 3
CodePudding user response:
Have you consider time change between summer and winter
CodePudding user response:
The Z in the date string 2020-09-22T17:10:25Z indicates that the time is in the UTC time zone, also known as Zulu time. When you create a new Date object using this string, the Date object will be initialized with the time in the UTC time zone.
When you call new Date() without any arguments, the Date object will be initialized with the current date and time in the local time zone. In your case, the local time zone is GMT 0200, so the Date object will be initialized with the current date and time in that time zone.
The reason you see a different time zone in the two cases is that the Date object automatically converts the time to the local time zone when it is displayed. In the first case, where the Date object is initialized with a time in the UTC time zone, the time is automatically converted to the local time zone (GMT 0200) when it is displayed. In the second case, where the Date object is already in the local time zone, no conversion is necessary and the time is displayed as-is.
If you want to initialize a Date object with a specific time in a specific time zone, you can use the Date.UTC() method to convert the time to the UTC time zone, and then pass that time to the Date constructor. For example, you could use the following code to create a Date object for the date and time specified in your question:
const date = new Date(Date.UTC(2020, 8, 22, 17, 10, 25));
CodePudding user response:
javascript's date() function works off of the time set on your local computer. if it is giving GMT 3
, then your computer is set to GMT 3
. check your system clock's configuration.
windows: https://kb.wisc.edu/helpdesk/page.php?id=79027
mac: https://support.apple.com/en-ca/guide/mac-help/mchlp2996/mac
linux: https://www.makeuseof.com/how-to-set-date-and-time-linux/