您如何使用 luxon / moment 判断日期时间是上午还是下午?

How do you tell if a datetime is am or pm using luxon / moment?

这个:

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}`);
});

发出这个:

2022-05-30T11:00:00Z: pm
2022-05-30T11:00:00+01:00: pm
2022-05-30T11:00:00-01:00: pm

这显然是错误的。

是的,错误的,因为2022-05-30T11:00:00+01:00不是那个时区pm

由于 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}`);
});

发出这个:

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

那么,正确的做法是什么?

...需要说明的是,我并不是要在没有时区的情况下 解析这些日期时间 ,而是试图以一种保留“UTC+X”时区,即 在原始日期字符串中

这可能吗?

使用:setZone: truefromISO.

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}`);
});