Search code examples
javascriptluxon

How to calculate a duration between two dates in luxon?


Luxon's documentation for the Duration.fromISO method describes it as

Create a Duration from an ISO 8601 duration string

Nowhere is mentioned the ability to create a duration based on two dates. My typical use case would be: "did the event between date ISODAT1 and ISODATE2 last more than an hour?".

What I will do is to transform the dates into a timestamp and check whether the difference is greater than 3600 (seconds), I believe however that there is a more native way to make the check.


Solution

  • You could use DateTime's .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>