【问题标题】:How to calculate a duration between two dates in luxon?如何计算luxon中两个日期之间的持续时间?
【发布时间】:2020-12-25 00:40:35
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript luxon


    【解决方案1】:

    你可以使用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>

    【讨论】:

    【解决方案2】:

    示例

    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 文档中,他们提到了持续时间和间隔。 如果您想知道某件事是否已经超过一个小时,您最好使用间隔,然后在间隔上调用.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)
    

    【讨论】:

    • 具有讽刺意味的是,在让我研究这个的项目中,我的队友最终建议我们使用类似的东西:DateTime.now().diff(DateTime.fromISO(date))
    猜你喜欢
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多