Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a specific DateTime is within a time interval using Luxon

I'm trying to figure out how to check if a specific DateTime is within a time interval. For example, let's say I have a variable named dateTimeToCheck and I want to see if it is within the first quarter of the year (Jan 1st to March 31st).

I could use diff between dateTimeToCheck and Jan 1st and then diff between dateTimeToCheck and March 31st followed by some calculations, but I feel like there should be a cleaner way using Luxon's Interval or something like that.

Any help is very much appreciated!

like image 964
risingTide Avatar asked Sep 02 '25 10:09

risingTide


1 Answers

Yes, you can use Luxon's Interval. The API has the contains method that:

Return whether this Interval contains the specified DateTime.

Here an example where I've used fromDateTimes to create Interval object:

const DateTime = luxon.DateTime;
const Interval = luxon.Interval;

const interval = Interval.fromDateTimes(DateTime.local(2023, 1, 1), DateTime.local(2023, 3, 31));
let dateTimeToCheck = DateTime.now();
console.log(interval.contains(dateTimeToCheck));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>
like image 52
VincenzoC Avatar answered Sep 04 '25 11:09

VincenzoC