Home > Enterprise >  I want to get New York time in this JavaScript clock?
I want to get New York time in this JavaScript clock?

Time:09-26

I want to get the New York time in this JavaScript. I tried with toLocaleTimeString('en-US', { timeZone: 'America/New_York' })

But it doesn't work.

Javascript:

setInterval(setClock, 1000)

const hourHandTK = document.querySelector('[data-hour-hand-tk]')
const minuteHandTK = document.querySelector('[data-minute-hand-tk]')
const secondHandTK = document.querySelector('[data-second-hand-tk]')

function setClock() {

var currentDate = new Date()
  const secondsRatio = currentDate.getSeconds() / 60
  const minutesRatio = (secondsRatio   currentDate.getMinutes()) / 60
  const hoursRatio = (minutesRatio   currentDate.getHours()) / 12
  setRotation(secondHandTK, secondsRatio)
  setRotation(minuteHandTK, minutesRatio)
  setRotation(hourHandTK, hoursRatio)
}

function setRotation(element, rotationRatio) {
  element.style.setProperty('--rotation', rotationRatio * 360)
}

setClock()

Full code:

Thanks in advance.

CodePudding user response:

toLocaleTimeString converts your Date to a String.

This should work

const currentDate = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));

CodePudding user response:

Sure toLocaleTimeString('en-US', { timeZone: 'America/New_York' }) wont work, cuz it returns the time part of the date as a string (e.g: 9:19:06 AM)

In your case, I guess this would be the solution:

var currentDate = new Date(
    (new Date()).toLocaleString(
        'en-US',
        { timeZone: 'America/New_York' }
    )
)

CodePudding user response:

This is kind of your choice if you want to or not but if you want, try using nodejs, after you install it you can just install https://www.npmjs.com/package/moment and then the only code you need is

var moment = require("moment-timezone")

var june = moment(new Date());
june.tz('America/New_York').format('ha z');

if you would like I can also help you through the installing process.

  • Related