DEV Community

Aimal
Aimal

Posted on

3

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.

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (4)

Collapse
 
amedalen profile image
Aj

Thank you for this wonderful post, I got inspired so I created an app in python to retrieve time in any city.

dev.to/amedalen/time-finder-of-any...

Once again thank you and have a great time.

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay