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

时间:2019-07-01 19:53:10

标签: javascript angular luxon

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

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

这是聊天,因此消息需要在每个用户的时区中显示。

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

我试图以某种方式使用这些方法

DateTime.local() DateTime.setZone(localZone)

localZone是接收本地区域的变量,例如:“欧洲/巴黎”。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以简单地使用luxon fromMillis来解析时间戳(假设以毫秒为单位),或者使用fromSeconds来解析时间戳。您还可以通过zone选项使用给定的时区创建luxon对象。您可以使用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