[英]How do you tell if a datetime is am or pm using luxon / moment?
This:这个:
import {DateTime} from "luxon";
[
"2022-05-30T11:00:00Z",
"2022-05-30T11:00:00+01:00",
"2022-05-30T11:00:00-01:00",
].map(raw => {
var sysTime = DateTime.fromISO(raw);
var amPm = sysTime.hour < 12 ? "am" : "pm";
console.log(`${raw}: ${amPm}`);
});
Emits this:发出这个:
2022-05-30T11:00:00Z: pm
2022-05-30T11:00:00+01:00: pm
2022-05-30T11:00:00-01:00: pm
Which is clearly wrong.这显然是错误的。
Yes, it is wrong, because 2022-05-30T11:00:00+01:00
is not pm
in that timezone .是的,这是错误的,因为
2022-05-30T11:00:00+01:00
在那个时区不是pm
。
Since luxon automatically stores SystemZone
, you have to explicitly convert it to correct timezone, if you happen to know what it is, for example:由于 luxon 自动存储
SystemZone
,因此如果您碰巧知道它是什么,则必须将其显式转换为正确的时区,例如:
[
"2022-05-30T11:00:00Z",
"2022-05-30T11:00:00+01:00",
"2022-05-30T11:00:00-01:00",
].map(raw => {
var sysTime = DateTime.fromISO(raw);
var realTime = sysTime.setZone('UTC+1'); // <---- explicit
var amPm = realTime.hour < 12 ? "am" : "pm";
console.log(`${raw}: ${amPm}`);
});
Emits this:发出这个:
2022-05-30T11:00:00Z: pm <---- still wrong
2022-05-30T11:00:00+01:00: am <--- correct
2022-05-30T11:00:00-01:00: pm
So, what's the right way to do this?那么,这样做的正确方法是什么?
...and to be clear, I'm not trying to parse these date times without a timezone , I'm trying to parse them in a way that preserves the "UTC+X" timezone that is in the raw date string . ...并且要清楚,我不是试图在没有 timezone 的情况下解析这些日期时间,而是试图以保留原始日期字符串中的“UTC+X”时区的方式解析它们。
Is that possible?那可能吗?
use: setZone: true
in fromISO
.使用:
setZone: true
在fromISO
中。
import {DateTime} from "luxon";
[
"2022-05-30T11:00:00Z",
"2022-05-30T11:00:00+01:00",
"2022-05-30T11:00:00-01:00",
].map(raw => {
var sysTime = DateTime.fromISO(raw, {setZone: true});
var amPm = sysTime.hour < 12 ? "am" : "pm";
console.log(`${raw}: ${amPm}`);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.