如何在JavaScript实现的模拟时钟中获取并显示纽约时区时间
JavaScript模拟时钟显示纽约时间解决方案
问题原因
你调用toLocaleTimeString('en-US', { timeZone: 'America/New_York' })不生效的核心原因是:该方法仅会将日期对象转换为对应时区的时间字符串,而你原有代码是通过getHours()、getMinutes()、getSeconds()方法直接获取本地时区的时分秒数值,逻辑没有和你生成的时区字符串关联,自然不会生效。
解决方案
我们可以使用Intl.DateTimeFormatAPI直接获取指定时区的时分秒数值,该方法会自动处理夏令时等时区规则,比手动计算时差更准确。
修改后的核心JS代码
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]') // 初始化纽约时区时间格式化器 const nyTimeFormatter = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false // 关闭12小时制,避免换算错误 }) function setClock() { const currentDate = new Date() // 解析获取纽约时区的时分秒数值 const nyTimeParts = nyTimeFormatter.formatToParts(currentDate) const nyHours = Number(nyTimeParts.find(item => item.type === 'hour').value) const nyMinutes = Number(nyTimeParts.find(item => item.type === 'minute').value) const nySeconds = Number(nyTimeParts.find(item => item.type === 'second').value) // 原有旋转逻辑不变,替换为纽约时间数值即可 const secondsRatio = nySeconds / 60 const minutesRatio = (secondsRatio + nyMinutes) / 60 const hoursRatio = (minutesRatio + nyHours) / 12 setRotation(secondHandTK, secondsRatio) setRotation(minuteHandTK, minutesRatio) setRotation(hourHandTK, hoursRatio) } function setRotation(element, rotationRatio) { element.style.setProperty('--rotation', rotationRatio * 360) } setClock()
如果需要修改你项目中另一个时钟的时区,只要把对应setClock函数里的时分秒获取逻辑替换为上述纽约时间的获取逻辑即可,HTML和CSS代码不需要做任何调整。
内容的提问来源于stack exchange,提问作者Chow Lip
相关产品推荐
相关产品推荐

