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

43
Luxon的Duration.fromISO方法的文档描述为:

从ISO 8601时间段字符串创建持续时间

文档中没有提到基于两个日期创建一个持续时间的能力。我的典型用例是:"事件在ISODAT1和ISODATE2之间是否持续了一个小时以上?"

我的做法是将日期转换成时间戳并检查差值是否大于3600(秒),不过我相信有更本地化的方式来进行检查。

2个回答

74
你可以使用 DateTime.diff 方法(文档)。

返回两个日期时间之间的差异作为持续时间。

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>


2
此答案中链接的文档已经移动到 https://moment.github.io/luxon/#/math?id=diffs。 - Anibe Agamah
@AnibeAgamah 谢谢,我刚刚更新了链接。 - hgb123
1
这是API的文档链接,也很有用:https://moment.github.io/luxon/api-docs/index.html#datetimediff - Vadorequest

17

例子

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')

持续时间

Duration类表示时间量,例如“2小时7分钟”。

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'

时间段

时间段是指一段特定的时间,比如“从现在到午夜之间”。它实际上是由两个形成端点的日期时间对象组成的包装器。

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)

1
具有讽刺意味的是,在让我开始研究这个问题的项目中,我的队友最终建议我们采用类似于 DateTime.now().diff(DateTime.fromISO(date)) 的方法。 - CTS_AE
在这个例子中,如果我只想要 - 如果2小时或更短呢?即“时间差不能超过2小时”。 - Nikhil Nanjappa
1
@NikhilNanjappa 我想你可以从两个日期中减去,然后实例化一个持续时间,从而获取小时并进行检查。否则,根据上面的示例,您可以取两个日期,并使用 Interval.fromDateTimes(date1, date2).length('hours') - CTS_AE
谢谢@CTS_AE - 我改成了以下代码,现在可以正常工作了。if (durToObject.hours >= 2 && durToObject.minutes >= 1) { **错误** } - Nikhil Nanjappa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接