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.

var range = ['05:00','22:00'];

function isInRange(value, range) {
  return value >= range[0] && value <= range[1];
}

['04:59','08:30','23:15'].forEach(function(time) {
  console.log(time + ' is ' + (isInRange(time, range)? ' ':'not ') + 'in range');
});

// Alternatively
['04:59','23:15','08:30'].forEach(function(time) {
  var inRange = isInRange(time, range);
  console.log(time + ' is in range ' + (inRange? range : range.slice().reverse()).join(' - '));
});

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.

/^(([0-1][0-9])|(2[0-3])):[0-5][0-9]$/.test(time)

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:

function isInRange(value, range) {
  let re = /^(([0-1][0-9])|(2[0-3])):[0-5][0-9]$/;
  let [start, end] = range;
  // Validate values
  if ([value, start, end].some(value => !re.test(value))) {
    return;
  }

  // If start less than end, assume doesn't go over midnight
  if (start <= end) {
    return value >= start && value < end;
  
  // Otherwise, assume goes over midnight
  } else {
    return value >= start || value < end;
  }
}


// Range on same day midnight
let range = ['05:00', '22:00'];
['08:30','23:00','25:15'].forEach(value => {
  let inRange = isInRange(value, range);
  // Check returned value isn't undefined
  if (inRange === void 0) {
    console.log(`Invalid input: ${value}, [${range}]`);
  } else {
    console.log(`${value}: is ${inRange? '':'not'} in [${range}]`);
  }
});

// Range over midnight
range = ['22:00', '05:00'];
['08:30','23:00'].forEach(value => console.log(
 `${value}: is ${isInRange(value, range)? '':'not'} in [${range}]`
 ));

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

// Convert time in H:mm format to minutes
function timeToMins(time) {
  let re = /^(([0-1]?[0-9])|(2[0-3])):[0-5][0-9]$/;
  if (!re.test(time)) return;
  let [H, m] = time.split(':');
  return H * 60 + m * 1;
}

function isInRange(time, range) {
  // Input validation
  let re = /^(([0-1]?[0-9])|(2[0-3])):[0-5][0-9]$/;
  if ([time, ...range].some(time => !re.test(time))) {
    return;
  }
  // Convert times to minutes
  let [start, end] = range.map(time => timeToMins(time));
  time = timeToMins(time);

  // If start less than end, assume doesn't go over midnight
  if (start <= end) {
    return time >= start && time < end;

    // Otherwise, assume goes over midnight
  } else {
    return time >= start || time < end;
  }
}

// Range on same day midnight
let range = ['05:00', '22:00'];
['08:30', '23:00', '25:15'].forEach(value => {
  let inRange = isInRange(value, range);
  // Check returned value isn't undefined
  if (inRange === void 0) {
    console.log(`Invalid input: ${value}, [${range}]`);
  } else {
    console.log(`${value}: is ${inRange? '':'not'} in [${range}]`);
  }
});

// Range over midnight
range = ['22:00', '05:00'];
['08:30', '23:00'].forEach(value => console.log(
  `${value}: is ${isInRange(value, range)? '':'not'} in [${range}]`
));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement