javascript - 如何按原样将 UTC 时间戳导入 Luxon?(从瞬间迁移)
问题描述
我的应用程序中有这一行:
const createdOn: moment.Moment = moment.utc(created_on)
created_on
来自如下格式的 api 端点:
{
...,
created_on: "2019-03-08T15:32:26.285Z",
}
这基本上created_on
作为 UTC 时区导入。created_on
也是UTC
。因此,此方法不会破坏时区并正确导入 UTC。我也有这个:
这会在 UTC 时区生成当前时间戳。
moment.utc()
请注意,如果我只是将日期导入时刻,然后将其转换为 UTC,我的时间就会出错。默认情况下,Moment 假定给定日期等于当前访问者时区。我需要按原样导入时间。一直是UTC。
什么是等价物Luxon
?
解决方案
您可以使用DateTime.utc
并且可以查看Luxon 手册的For Moment users部分。
您可以在创建部分找到:
Operation | Moment | Luxon | Notes ------------------------------------------------------------------------------------ From UTC civil time | moment.utc(Array) | DateTime.utc(Number...) | Moment also uses moment.utc() to take other arguments. In Luxon, use the appropriate method and pass in the { zone: 'utc'} option
所以,如果你的输入是一个字符串,你可以使用from
方法(如fromISO
)使用{zone: 'utc'}
选项
这是一个现场样本:
const DateTime = luxon.DateTime;
const nowLuxon = DateTime.utc();
console.log(nowLuxon.toISO(), nowLuxon.toMillis());
const nowMoment = moment.utc();
console.log(nowMoment.format(), nowLuxon.valueOf());
const created_on = "2019-03-08T15:32:26.285Z";
const createdOnLuxon = DateTime.fromISO(created_on, { zone: 'utc'});
console.log(createdOnLuxon.toISO(), createdOnLuxon.toMillis());
const createdOnMoment = moment.utc(created_on);
console.log(createdOnMoment.format(), createdOnMoment.valueOf());
<script src="https://cdn.jsdelivr.net/npm/luxon@1.21.3/build/global/luxon.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
推荐阅读
- r - 在 (R, ggplot2) 中的条形和类别周围绘制一个矩形
- xml - 在groovy中对xml节点进行排序
- sql - Groovy JDBC:如何使用准备好的语句更新表,其中在更新字段之前必须满足条件
- node.js - Knex - 如何确定在事务期间失败的查询
- aws-glue - 根据特定 id 过滤掉行 - Glue Job
- python - Python PyPDF2 合并不允许 os.remove 工作
- .net-core - .Net 核心微服务查询来自许多服务
- php - 具有自定义 slug 的自定义帖子类型和其他页面的 404 错误
- sql - 如何从一个纪元中提取一天中的小时并计算该小时内发生的每个实例?
- quarkus - Quarkus HTTP authentication logout