gpt4 book ai didi

JavaScript UTC 到本地日期的转换在 IE 和 Firefox 中不起作用,但在 Chrome 中工作正常

转载 作者:行者123 更新时间:2023-11-28 17:16:04 26 4
gpt4 key购买 nike

我遇到了一个问题。

我使用 Java 代码在服务器中保存 UTC 时间:

DateFormat timeFormat = new SimpleDateFormat("dd-MMMM-yy HH:mm:ss");

我坚持这样做 ->

time = timeFormat.format(new Date()).toString()

这将保留为 UTC 时间。

现在,在浏览器中显示它时,我将其转换为本地时间:

var date = new Date(time);

convertToLocal(date).toLocaleString();

function convertToLocal(date) {
var newDate = new Date(date.getTime() +date.getTimezoneOffset()*60*1000);

var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();

newDate.setHours(hours - offset);

return newDate;
}

console.log("Time : " + convertToLocal(date).toLocaleString())

这在 Chrome 中工作正常,但在 Firefox 和 IE 中,我得到“无效日期”而不是我期望看到的时间戳。

请帮忙。

最佳答案

问题是您的 Java 代码生成的日期/时间字符串不符合 ISO 8601 format 。 JavaScript 引擎必须如何处理这一点尚未定义(因此不同浏览器之间存在差异)。

参见How to get current moment in ISO 8601 format with date, hour, and minute?了解如何更改 Java 代码以生成使用 ISO 格式的日期。您只需将所需的格式 (ISO) 传递给 SimpleDateFormat 并将其配置为 UTC:

DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

该输出应类似于 2018-11-26T19:41:48Z(接受其多种变体)。请注意“T”和终止符“Z”(代表 UTC)。

完成后,JavaScript 将正确地将日期/时间解释为 UTC 时区中指定的日期/时间,然后您只需在 JavaScript 中执行以下操作,无需显式添加时区差异:

console.log("Time : " + date.toLocaleString())

JavaScript 将在字符串化中考虑本地时区。

关于JavaScript UTC 到本地日期的转换在 IE 和 Firefox 中不起作用,但在 Chrome 中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53483634/

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