如何在时间标签和相同的类中以UTC格式重新格式化ISO 8601时间戳,并通过JavaScript根据用户区域设置和时区

How to reformat ISO 8601 timestamps in UTC in time tags and same classes and adjust to user locale and timezone via JavaScript?

本文关键字:8601 时间戳 JavaScript 设置 时区 区域 用户区 ISO 用户 标签 时间      更新时间:2023-09-26

如何在时间标签和相同的类中重新格式化UTC中的ISO 8601时间戳,并通过JavaScript根据用户区域设置和时区进行调整?

我确实有一个html页面,其中有一个带有多个UTC ISO 8601格式时间戳的表,包含在html时间标签中,并被赋予相同的类。

我想将它们重新格式化为已更正的用户区域设置格式和时区。

我想出了下面的代码。在上述评论中,我需要在TODO中添加什么?

<!--- table with timestamps in ISO 8601 format and UTC --->
<table>
<tr><td>1: </td><td><time class="UTC_ISO_Date">2013-02-07T23:00:00.000Z</time></td></tr>
<tr><td>2: </td><td><time class="UTC_ISO_Date">2015-06-09T21:30:00.000Z</time></td></tr>
<tr><td>3: </td><td><time class="UTC_ISO_Date">2016-03-022T09:00:00.000Z</time></td></tr>
</table>
// get the timezone of the user out of the browser
var timezone = jstz.determine();
var usertz = timezone.name();
// TODO: get the locale of the user out of the browser    
// iterate over classes="UTC_ISO_Date" with each()
$('.UTC_ISO_Date').each(function(i, obj) {      
    // format the timestamps into the correspondent format of the user locale and adjust to the users timezone
    var formattedTimestamp = moment(i);
    // TODO: update the value in the current class
});

在这种情况下,您不需要知道用户的时区。您不需要jsTimeZoneDetect或即时时区。您可以简单地拨打:

moment('2013-02-07T23:00:00.000Z').format()

您可以将所需的参数传递给format函数。有关详细信息,请参阅即时文档。

此外,大多数现代浏览器都会对Date对象执行此操作,只是对输出格式没有那么多控制权。

new Date('2013-02-07T23:00:00.000Z').toString()