简体   繁体   中英

How to check time between range using javascript

I have the time value in HH:MM format. Hours are in 24 hours format. eg 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.

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(' - ')); });

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM