将日期转换为 JavaScript 中的另一个时区并使用正确的时区打印

Convert Date to another timezone in JavaScript and Print with Correct Timezone

我需要将本地时区转换为 Pacific/Los 安吉利斯。

例如,如果用户在夏威夷

代码: 取自

function convertTZ(date, tzString) {
    return new Date((typeof date === "string" ? New Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));   
}

convertTZ(new Date(), "America/Los_Angeles")

Sun Mar 14 2021 17:01:59 GMT-1000 (Hawaii-Aleutian Standard Time) {}

它仍然打印与夏威夷的决赛。我需要 America/Los Angeles Display,而不是夏威夷。 (但是它仍然打印正确的新小时和分钟,只是显示标签不正确) 如何做到这一点?

该解决方案也适用于其他时区,分别打印其他时区,例如:America/New_York、Europe/London、Europe/Paris 等,

function convertTZ() {
    return new Date().toLocaleString('en-US', { timeZone: "America/Los_Angeles" });
}
console.log(convertTZ());

//Second way
//Hoepfully that's going to be the code that you need.You can change the way that you want to see the date.
function convertTZ() {
    return new Date().toLocaleString('en-US', {
    timeZone: "America/Los_Angeles" ,
  day: "numeric",
  month: "short",
  year: "numeric",
  hour: "numeric",
  minute: "2-digit"
});
}
console.log(convertTZ(),' America/Los Angeles');

根据您的要求, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions 将有助于实现它。

几件事:

  • 您链接到 convertTZ 的答案中的方法存在缺陷。不应使用 Date 构造函数解析 toLocalString 的输出。请阅读该答案后的评论。

  • Date对象不能转换到另一个时区,因为它实际上不在任何 时区。 Date 对象唯一封装的是它的 Unix 时间戳,可以通过 .valueOf().getTime() 或任何将其强制为 Number 的机制看到。这些值始终基于 UTC。

  • 当您看到来自 Date 对象的本地时间或时区时,系统的本地时区将应用于基于 UTC 的内部 Unix 时间戳以创建输出。不能从 JavaScript(或 TypeScript)以编程方式更改本地时区,也不能在每个对象的基础上进行更改。

  • 与其尝试将一个时区的 Date 对象转换为另一个时区的 Date 对象,不如认识到所有 Date 对象本质上都是世界标准时间。因此,您可以创建一个处于不同时区的 string(例如,使用带有 timeZone 选项的 toLocaleString)但您不能创建一个新的Date 来自该字符串的对象。如果您想要一个实际上可以设置为不同时区的对象,请考虑 Luxon. If you need a solution without a library, you will one day be able to use a ZonedDateTime from the TC39 Temporal Proposal,它最终将成为 ECMAScript 的一部分。

  • 注意在 Date 对象上调用 console.log。 ECMAScript 规范和 WhatWG 控制台规范均未定义此类调用的行为。这是未定义的行为。在某些环境中,记录的字符串输出与在 Date 对象上调用 .toString() 相同 - 这将给出相当于 Date 对象时间戳的本地时间,以及显示名称本地时区。其他环境将显示调用 .toISOString() 的相同输出,这将给出 UTC 时间戳的 ISO-8601 表示。不要记录 Date 个对象,而是自己调用这两个函数之一并记录输出。