1

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.

aslamdoctor
  • 3,753
  • 11
  • 53
  • 95
  • 1
    could you show us, what did you tried so far ? – Ravi Jul 20 '17 at 04:08
  • Have you tried anything so far? StackOverflow isn't a free code-writing service, and expects you to [**try to solve your own problem first**](http://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried, showcasing all of your relevant code in a [**minimal, complete, and verifiable example**](http://stackoverflow.com/help/mcve). – Obsidian Age Jul 20 '17 at 04:09
  • Possible duplicate of [check if one date is between two dates (javascript)](https://stackoverflow.com/questions/16080378/check-if-one-date-is-between-two-dates-javascript) – Ravi Jul 20 '17 at 04:10
  • @Ravi—the OP doesn't have dates and doesn't need them. – RobG Jul 20 '17 at 04:23

2 Answers2

5

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}]`
));
RobG
  • 142,382
  • 31
  • 172
  • 209
  • `Attention: This is a faulty solution`, at least if you need to compare values that stretch above '00:00'. For example: isInRange("12:00", ['11:00', '02:00']) will return 'false' when it should be true. Also the explanation is wrong: `HH:mm format are not compared directly`, all it does is compare the strings character codes. For example: '12abc15' > '12abc00' will return true, but not because it compares 'times' just character codes. If you need a real general and battle tested solution for time handling, always use a library especially made for it. – Aerodynamic Jan 15 '22 at 17:29
  • @Aerodynamic—clearly logic for ranges that extend over midnight is different to those that don't. The answer provides a method, not a complete solution. Similarly, validation of input is a separate concern and may be implemented by the caller or callee. If you want to address those concerns, post an answer. :-) – RobG Jan 15 '22 at 21:36
  • Hi Rob. As pointed out, your code might work within the specific constrains (['05:00','22:00']) as stated by the OP. However, as must people on SO are looking for general solutions, I find it important to clearly state that this is not a general solution where you can just put in any range and it will work. Maybe you could note the limits of this method in your answer and possible correct how you implied comparison works. . I'm trying to figure out the 00:00 span myself and when done might post it here. – Aerodynamic Jan 15 '22 at 21:51
  • This will not work for ranges like ` ['23:00','02:00']` – Eugene Mala Jan 17 '22 at 01:44
  • @EugeneMala—where the start is a later time than the end, it is assumed that the range is over midnight so ['23:00','02:00'] works as expected, e.g. 23:30 is in range, 03:00 is not. Examples are included in the above. If the requirement is to work with times that don't fit that criterion, then a date (or some other mechanism to identify that the range is over midnight) is required. – RobG Jan 17 '22 at 03:12
0

Try this code snippet

function dateObj(d) {
    var parts = d.split(":"),
        date  = new Date();

    date.setHours(parts[0]);
    date.setMinutes(parts[1]);
    return date;
}
if(dateObj('02:35')>= dateObj('14:30')&& dateObj('14:30')<=dateObj('22:00'))alert('true');
Joey Pinto
  • 1,735
  • 1
  • 18
  • 34