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

WoJ*_*WoJ 18 javascript luxon

Duration.fromISO方法的Luxon文档将其描述为

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

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

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

hgb*_*123 28

你可以使用DateTime's .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())
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 此答案中链接的文档似乎已移至 https://moment.github.io/luxon/#/math?id=diffs (2认同)

CTS*_*_AE 18

例子

\n
const date1 = luxon.DateTime.fromISO("2020-09-06T12:00");\nconst date2 = luxon.DateTime.fromISO("2019-06-10T14:00");\nconst diff = Interval.fromDateTimes(later, now);\nconst diffHours = diff.length(\'hours\');\n\nif (diffHours > 1) {\n  // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Luxon v2.x 文档

\n

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

\n\n

持续时间

\n
\n

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

\n
\n
const dur = Duration.fromObject({ hours: 2, minutes: 7 });\n\ndur.hours;   //=> 2\ndur.minutes; //=> 7\ndur.seconds; //=> 0\n\ndur.as(\'seconds\'); //=> 7620\ndur.toObject();    //=> { hours: 2, minutes: 7 }\ndur.toISO();       //=> \'PT2H7M\'\n\n
Run Code Online (Sandbox Code Playgroud)\n

间隔

\n
\n

间隔是特定的时间段,例如“从现在到午夜”。它们实际上是形成其端点的两个日期时间的包装器。

\n
\n
const now = DateTime.now();\nconst later = DateTime.local(2020, 10, 12);\nconst i = Interval.fromDateTimes(now, later);\n\ni.length()                             //=> 97098768468\ni.length(\'years\')                      //=> 3.0762420239726027\ni.contains(DateTime.local(2019))       //=> true\n\ni.toISO()       //=> \'2017-09-14T04:07:11.532-04:00/2020-10-12T00:00:00.000-04:00\'\ni.toString()    //=> \'[2017-09-14T04:07:11.532-04:00 \xe2\x80\x93 2020-10-12T00:00:00.000-04:00)\n
Run Code Online (Sandbox Code Playgroud)\n