如何计算 luxon 中两个日期之间的持续时间?

How to calculate a duration between two dates in luxon?

Luxon 的 documentation for the Duration.fromISO method 将其描述为

Create a Duration from an ISO 8601 duration string

没有提到根据两个日期创建持续时间的能力。我的典型用例是:“日期 ISODAT1 和 ISODATE2 之间的事件是否持续了一个多小时?”

我要做的是将日期转换为时间戳并检查差异是否大于 3600(秒),但是我相信有更原生的方法来进行检查。

您可以使用 DateTime.diff (doc)

Return the difference between two DateTimes as a Duration.

const date1 = luxon.DateTime.fromISO("2020-09-06T12:00")
const date2 = luxon.DateTime.fromISO("2019-06-10T14:00")

const diff = date1.diff(date2, ["years", "months", "days", "hours"])

console.log(diff.toObject())
<script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>

例子

const date1 = luxon.DateTime.fromISO("2020-09-06T12:00");
const date2 = luxon.DateTime.fromISO("2019-06-10T14:00");
const diff = Interval.fromDateTimes(later, now);
const diffHours = diff.length('hours');

if (diffHours > 1) {
  // ...
}

Luxon 文档 v2.x

在 Luxon 文档中,他们提到了持续时间和间隔。 看来你最好使用 Intervals 然后在 Interval 上调用 .length('hours') 如果你有兴趣知道某件事是否已经超过一个小时。

时长

The Duration class represents a quantity of time such as "2 hours and 7 minutes".

const dur = Duration.fromObject({ hours: 2, minutes: 7 });

dur.hours;   //=> 2
dur.minutes; //=> 7
dur.seconds; //=> 0

dur.as('seconds'); //=> 7620
dur.toObject();    //=> { hours: 2, minutes: 7 }
dur.toISO();       //=> 'PT2H7M'

间隔

Intervals are a specific period of time, such as "between now and midnight". They're really a wrapper for two DateTimes that form its endpoints.

const now = DateTime.now();
const later = DateTime.local(2020, 10, 12);
const i = Interval.fromDateTimes(now, later);

i.length()                             //=> 97098768468
i.length('years')                      //=> 3.0762420239726027
i.contains(DateTime.local(2019))       //=> true

i.toISO()       //=> '2017-09-14T04:07:11.532-04:00/2020-10-12T00:00:00.000-04:00'
i.toString()    //=> '[2017-09-14T04:07:11.532-04:00 – 2020-10-12T00:00:00.000-04:00)