Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a duration between two dates in luxon?

Tags:

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.

like image 516
WoJ Avatar asked Sep 06 '20 10:09

WoJ


People also ask

How do I calculate the number of minutes between two dates?

To get the number of minutes between 2 dates: Get the number of milliseconds between the unix epoch and the Dates. Subtract the milliseconds of the start date from the milliseconds of the end date. Divide the result by the number of milliseconds in a minute - 60 * 1000 .

How do you calculate the difference between two dates in react?

To compare the date and time portions of the date instance of two dates, use isEqual function. Copy Code import { isEqual } from '@progress/kendo-date-math'; const date1 = new Date(2000, 10, 10); const date2 = new Date(2000, 10, 10, 10); const equal = isEqual(date1, date2); // Returns false.

What is Luxon date?

Luxon is a library for dealing with dates and times in JavaScript. DateTime.


1 Answers

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/[email protected]/build/global/luxon.min.js"></script>
like image 71
hgb123 Avatar answered Sep 19 '22 07:09

hgb123