Angular/Javascript Luxon - 将时间戳更改时间转换为当前用户时区

Angular/Javascript Luxon - Convert timestamp changing time to current user timezone

我从数据库中得到了一个时间戳,我需要在用户的时区中显示它的时间。

例如:巴西16:42,法国21:42。

这是一个聊天,所以消息需要显示在每个用户的时区。

我在项目中有 luxon,但在这种情况下我无法使用任何对我有帮助的文档。

我尝试过在某些方面使用这些方法

DateTime.local()DateTime.setZone(localZone)

localZone是接收本地区域的变量,例如:"Europe/Paris".

谢谢!

您可以简单地使用 luxon fromMillis to parse timestamp (assuming that it is in milliseconds) or fromSeconds if it is in seconds. You can also pass zone option to create luxon object using given timezone. The you can use toFormat() 以您想要的格式显示时间。你可以有类似下面的东西:

DateTime.fromMillis(timestamp, {zone: localZone}).toFormat('HH:mm')

如果需要,您也可以使用 setZone 更改区域 属性,这里是使用示例数据的片段:

const DateTime = luxon.DateTime;
let curTimestamp = 1562061791000;
let time = DateTime.fromMillis(curTimestamp)
console.log('Local time:', time.toFormat('HH:mm') );
console.log('Brazil time:',  time.setZone('America/Sao_Paulo').toFormat('HH:mm') );
console.log('France time:', DateTime.fromMillis(curTimestamp, {zone: 'Europe/Paris'}).toFormat('HH:mm') );
<script src="https://cdn.jsdelivr.net/npm/luxon@1.16.0/build/global/luxon.js"></script>

如果您想在 Angular 视图中使用 Luxon,请查看 luxon-angular