Comparing times only within an interval in js

60 views Asked by At

I am trying to compare only time (regardless of the date) in js. First I need a way to compare times so I came across the luxon library which works well.

But, there is a problem when comparing intervals across midnight. For example: 20:00 < 01:00 < 10:00 should evaluate to true, the luxon's library returns a false. Which makes sense because 20:00 < 01:00 can evaluate differently when in different intervals. These is what I would be expecting:

20:00 < 01:00 < 10:00 == true // but it evaluates as false using luxon's interval

00:00 < 01:00 < 10:00 == true

This is the code I have so far:

const from = DateTime.fromISO('20:00');
const to = DateTime.fromISO('10:00');
const value = DateTime.fromISO('01:00');

const interval = Interval.fromDateTimes(from, to);

console.log(interval.contains(valueTime)); // returns false instead of true
2

There are 2 answers

1
Helge Derenthal On

Substract on day from from, if from is bigger than to. And substract on day from value, if it is bigger than to, to get it into the interval.

let from = luxon.DateTime.fromISO('20:00');
const to = luxon.DateTime.fromISO('10:00');
let value = luxon.DateTime.fromISO('01:00');

if(from > to)
{
  from = from.minus({ days: 1 });
}

if(value > to)
{
  value = value.minus({ days: 1 });
}

const interval = luxon.Interval.fromDateTimes(from, to);

console.log(interval.contains(value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.4.3/luxon.min.js" integrity="sha512-gUQcFuEaDuAEqvxIQ9GDdMcCeFmG5MPnoc6ruJn+nyCNHrHM2oB97GOVLIOiixzTxPYmIfEQbOoQmx55UscLyw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Testing different values:

19:00 -> false
21:00 -> true
01:00 -> true
09:00 -> true
11:00 -> false

Seems to be the desired behavior.

0
mplungjan On

You need the date unless the to is always smaller than the from across midnight

const from = luxon.DateTime.fromISO('2023-11-03T20:00');
const to = luxon.DateTime.fromISO('2023-11-04T10:00');
const valueTime = luxon.DateTime.fromISO('2023-11-04T01:00');

const interval = luxon.Interval.fromDateTimes(from, to);
console.log(from.toString(),"\n",to.toString(),"\n",valueTime.toString())
console.log(interval.contains(valueTime)); // returns false instead of true
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.4.3/luxon.min.js" integrity="sha512-gUQcFuEaDuAEqvxIQ9GDdMcCeFmG5MPnoc6ruJn+nyCNHrHM2oB97GOVLIOiixzTxPYmIfEQbOoQmx55UscLyw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>