Skip to content
Advertisement

How to check time between range using javascript

I have the time value in HH:MM format. Hours are in 24 hours format. e.g. 14:30

I want to do a checking using two IF condition

  1. if the time value is between 05:00 to 22:00
  2. if the time value is between 22:00 to 05:00

I am not sure how to do that.

Advertisement

Answer

Since times in HH:mm format can be compared directly, you just need to compare the values. The following returns true if the time is in range, false otherwise.

JavaScript

To provide more robust code, the input should be validated and cases over midnight should be considered.

Validation should limit hours to the range 00-23 and minutes to the range 00 to 59, e.g.

JavaScript

If the start time is less than the end time, assume that the range doesn’t go over midnight, e.g. 05:00 to 22:00. If the start is greater than the end, the range does go over midnight, so:

JavaScript

If comparing strings doesn’t suit, times can be reduced to a common unit, say minutes and then compared, e.g.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement