gpt4 book ai didi

javascript - 如果未检测到时区,则无法强制执行运行时时区

转载 作者:行者123 更新时间:2023-11-30 06:11:02 25 4
gpt4 key购买 nike

我正在尝试获取日期/时间,我的代码(如下)运行良好。不幸的是,在早期版本的 chrome 上,它无法检测时区并给出错误 -

RangeError: Invalid time zone specified: undefined
at new DateTimeFormat (native)
at Date.toLocaleString (native)

.因此,当未检测到运行时时区时,我需要帮助将其强制为 UTC。有人可以帮忙吗?

这是我的代码:

 const printedDate = new Date;
const printedDateStringFormatted = printedDate.toLocaleString();

如果我不够清楚地说明我的问题,请告诉我。

最佳答案

如果您无法检测到本地时区,则可以捕获错误,在这种情况下使用 UTC。

const printedDate = new Date;
let printedDateStringFormatted;

try {
printedDateStringFormatted = printedDate.toLocaleString();
} catch (e) {
const options = { timeZone: 'UTC', timeZoneName: 'short' };
printedDateStringFormatted = printedDate.toLocaleString(undefined, options);
}

// Local datetime if available, otherwise will be datetime in UTC
console.log(printedDateStringFormatted);

关于javascript - 如果未检测到时区,则无法强制执行运行时时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com