DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Aimal
Aimal

Posted on

How to get a city's current time independent of user's current time in JS?

I have a problem in JS which I couldn't find an exact answer online (even on StackOverFlow). Basically, I have created 3 clocks to show current times of New York, Sydney and Tokyo. I use Date() function then converting it toLocaleString to get exact time of those cities but the problem is that if my system's time is incorrect then those clocks will also show incorrect time because JS is a client side language. Is there an easy way so that I get the local time of NY, Sydney and Tokyo without using Date()?

My current code is here:

var countryTimeZone = new Date(now.toLocaleString('en-US', { timeZone: 'Asia/Tokyo' }));
    var time = countryTimeZone.getHours() * 3600 +
        countryTimeZone.getMinutes() * 60 +
        countryTimeZone.getSeconds() * 1 +
        countryTimeZone.getMilliseconds() / 1000
    rotate(secondElement, time)
    rotate(minuteElement, time / 60)
    rotate(hourElement, time / 60 / 12)

Thank you so much.

Top comments (4)

Collapse
 
fasani profile image
Michael Fasani

You would pass the time from the backend to the frontend and store it on the page. Something like β€˜window.currentServerTime’.

If your doing XHR sometimes you can get it from the headers. β€˜ xhr.getResponseHeader(β€œDate”)’.

Collapse
 
manishfoodtechs profile image
manish srivastava

javascriptkit.com/dhtmltutors/loca...

Seems, you searching this!!!

Collapse
 
daviddalbusco profile image
David Dal Busco

You can probably use the Intl.DateTimeFormat Web API

🀯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs