Search code examples
javascriptluxon

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!


Solution

  • 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/luxon@3.2.1/build/global/luxon.min.js"></script>