[英]How to calculate a duration between two dates in luxon?
Luxon 的Duration.fromISO
方法文档将其描述为
从 ISO 8601 持续时间字符串创建持续时间
没有提到基于两个日期创建持续时间的能力。 我的典型用例是: “日期 ISODAT1 和 ISODATE2 之间的事件是否持续了一个多小时?” .
我要做的是将日期转换为时间戳并检查差异是否大于 3600(秒),但是我相信有一种更原生的方法来进行检查。
你可以使用DateTime
的.diff
( doc )
将两个 DateTime 之间的差异作为 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 文档中,他们提到了持续时间和间隔。 如果您有兴趣知道某事是否已经超过一个小时,您似乎最好使用 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'
间隔是特定的时间段,例如“从现在到午夜之间”。 它们实际上是形成其端点的两个 DateTime 的包装器。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.