I have been confused by converting time zones in Angular for several days, it turns out that UTC ISO date formats need to add a letter “Z” at the end which means zero offset1. So what happens if we left it out?
With “Z”, Firefox will create a
Date object with the same time. Without “Z”, you will get a time with offset, it depends on your local time zone.
With “Z”, Chrome will convert the UTC time to your local time zone. Without “Z”, you get the same time but with your local time zone!
Safari doesn’t care the letter “Z” at all, it will convert to your local time zone anyway.
In some shitty Chinese Android browsers
These basters don’t support
options parameters of
- Get the current UTC time in ISO format:
If you want to create a UTC
Dateobject, you should use
If you want to get the local time zone name, use this:
If you want to get the offset times, use
Keep in mind that this method:
returns the time zone difference, in minutes, from current locale (host system settings) to UTC.
In this case, it means that UTC time is after the local time(UTC+8) 480 minutes. And sometimes, Firefox will return 0!
In Angular, if you use Datepipe, it will convert to your local time by default. But you can also set it manually, by passing the
timezone parameter. For example,
"+0800" means the local time is 8 hours before UTC time3.
dateString to create
Date objects, as MDN noted:
parsing of date strings with the
Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. “1970-01-01”) are treated as UTC, not local.
If you have to use it, make sure you add the letter “Z”. Then use
toLocaleString() , we can convert UTC to your local time zone with formate(except some gross Android browsers).
toLocaleString() will use your local time zone by default unless you set the
You see, I’ve learned something today, yesterday and the day before yesterday: ****