0

Been trying to wrap my head around this for a good time now, but I can't think of a good way to do it.

I have an array with a bunch of different UTC time zones (in just format -07, -01, +03, +10, etc). What I'm trying to achieve is a way to show the local time of those time zones, possibly including the day and month.

Here's an example of the resulting string: Local time: 14:09 23/08

asked Jul 23, 2021 at 14:40
2
  • You can read about how to mange date and time in JS here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 23, 2021 at 14:47
  • You can use Date.prototype.getTimezoneOffset() to get your local timezone. Calculate the difference between your local timezone and the destination timezone, multiply it with 3600000 and add it to a Date object containing the current time. Commented Jul 23, 2021 at 14:51

1 Answer 1

1

You can use Date.prototype.getTimezoneOffset() to get your local timezone. Calculate the difference between your local timezone and the destination timezone, multiply it with 3600000 and add it to a Date object containing the current time.

const now = new Date();
const timezoneOffset = now.getTimezoneOffset() / 60;
const timezones = ['-07', '-01', '+03', '+10'];
timezones.forEach(timezone => {
 const difference = +timezone + timezoneOffset;
 const time = new Date(now.getTime() + difference * 3600000);
 console.log(`Local time: ${time.toLocaleTimeString([], { timeStyle: 'short', hour12: false })} ${time.toLocaleDateString([], { month: '2-digit', day: '2-digit' })}`);
});

answered Jul 23, 2021 at 15:07

3 Comments

How can I change this to a European format? Currently displays the time in 12 hr mm/dd which is the opposite of what I specified in the post. Edit: also, the code gives me the incorrect time by 3 hours, possibly because I'm on UTC+03 myself and the code thinks I'm on UTC+00?
Update: I managed to change the formatting, but I'm still not sure how to fix the time being incorrect...
@Piipperi800 I fixed it. getTimezoneOffset() returns the negative of what I expected.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.