-3

I have a variable that stores a time value.

var cabtime = ["09:30:00"];

Variable time value is in 24-hour clock. That means 02:30:0PM will come as 14:30:00.

I want to check if the variable time falls under 08:00AM to 10:00AM window. If yes then I'll do an action.

Any pointers in this regard?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64

2 Answers2

1

You could parse the time into seconds since midnight using:

var cabtime = ["HH:MM:SS"] // in 24hr time

function parseTime (string) {
    parts = string.split(':').map(x => parseInt(x))
    seconds = parts[0] * 3600 + parts[1] * 60 + parts[0]
    return seconds
}

Then you can parse the time and the upper/lower bounds, and test using:

time = parseTime(cabtime[0])
lower = parseTime('08:00:00')
upper = parseTime('10:00:00')

if (time >= lower && time <= upper) {
    print('Inside the range')
}
Oliver
  • 1,576
  • 1
  • 17
  • 31
0

You can solve it easily by converting your strings to Date objects and compare them than.

var cabtime = ["09:30"];

function checkTimeRange(time, from, to, reldate) {
    if (undefined === reldate) {
        reldate = '0000T'; // the date the time strings are related to
    }

    let dtime = new Date(reldate + time);
    let dfrom = new Date(reldate + from);
    let dto   = new Date(reldate + to);

    return dfrom <= dtime && dtime <= dto;
}

checkTimeRange(cabtime[0], '08:00', '10:00'); // returns true

If you have full dates (e.g. '2019-07-25T09:30:00') instead of just the clock time you should provide for the parameter `reldate' an empty string.


* update: changed the wrong date format to standard format

* update: changed the date format again to be more fancy

bukart
  • 4,906
  • 2
  • 21
  • 40
  • 1
    This does not work in some browsers. See [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) – str Jun 25 '19 at 10:59
  • 1
    @AmbikaTewari This code breaks in Firefox, Safari, and maybe others. It uses invalid date formats and you most definitely should not use it. – str Jun 25 '19 at 11:31