Orlando
Orlando

Reputation: 975

How to display times in different time zones using the offset value

I am trying to display the current moment in different time zones. I have tried to use native javascript and the moment-js package but it seems you require the time zone name (ex. "America/Toronto") to display the information I want. The problem is that the information I currently have is the timestamp in string format (see below for string format) from the desired timezone, and the city the timestamp belongs to. The problem with using the city to create my tz value is that one of the cities I want to display isn't in the IANA tz database (Calgary).

String timestamp:

2022-04-26T14:19:42.8430964-04:00

As can be seen I do have the time offset and I was hoping there was a way to convert this string in js to a Date object and then display the time using the offset in the correct time zone.

Note what I want to display is the following format:

12:19 pm MT

I know I could just parse out the string but I feel like this isn't the best practice, however I may be wrong.

Also note that I will have to get the time zone (ex. MT, ET it can also be MST, EST) using the offset.

Upvotes: 0

Views: 399

Answers (1)

Liam
Liam

Reputation: 29634

you don't need moment here. JS can do this natively. Also moment is now deprecated.

Your IANA timezone is America/Edmonton. So it's simple to do. That date format is an ISO 8601 date format, so you can just pass it into the new Date constructor and it'll parse it correctly:

const iso8601 = '2022-04-26T14:19:42.8430964-04:00';
const date = new Date(iso8601);
console.log(date.toLocaleString('en-US', { timeZone: 'America/Edmonton' }));

It doesn't matter what timezone your input date is set, so long as it has the correct offset in the ISO date. Once it's a Date, the offset is irrelevant. E.g.:

const iso8601 = '2022-04-26T14:19:42.8430964Z';
const date = new Date(iso8601);
//time will now be 4 hours off above as the input date is UTC
console.log(date.toLocaleString('en-US', { timeZone: 'America/Edmonton' }));

Upvotes: 4

Related Questions