【问题标题】:JavaScript function for 3 different timezones适用于 3 个不同时区的 JavaScript 函数
【发布时间】:2022-01-08 08:24:26
【问题描述】:

我对下面的时钟代码有疑问。如何调整三个不同时区的功能?在这种情况下我应该使用 Class 吗?

const secondHand = document.getElementById("second_hand");
const minsHand = document.getElementById("min_hand");
const hourHand = document.getElementById("hour_hand");

function setDate() {
  const now = new Date(); 

  const seconds = now.getSeconds();
  const secondsDegrees = (seconds / 60) * 360 + 90; 
  secondHand.style.transform = `rotate(${secondsDegrees}deg)`;

  const mins = now.getMinutes();
  const minsDegrees = (mins / 60) * 360 + (seconds / 60) * 6 + 90;
  minsHand.style.transform = `rotate(${minsDegrees}deg)`;

  const hour = now.getHours();
  const hourDegrees = (hour / 12) * 360 + (mins / 60) * 30 + 90;
  hourHand.style.transform = `rotate(${hourDegrees}deg)`;
}
setInterval(setDate, 1000);
setDate();

【问题讨论】:

  • JavaScript 在浏览器中运行(除非您使用的是节点),因此无论系统时间设置如何,它都会得到。

标签: javascript timezone


【解决方案1】:

日期构造函数具有.toLocaleString() 函数,它将返回特定时区的当前日期/时间(假设您只使用现代网络浏览器/节点版本)。

例如: let newYorkTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

查看这个问题了解更多信息:How to initialize a JavaScript Date to a particular time zone

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 2013-05-24
    • 2017-11-22
    • 1970-01-01
    • 2020-06-05
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多