Varun Sreedharan Varun Sreedharan - 1 month ago 6
Javascript Question

Check if Array contains a specific time

I have one array that contains some time intervals, I want to check if the array the current time(HH:mm) is inside the array or not . Time format may be

30 min or 60 minutes
interval
(9:30,10:30 || 9:00,10:00)
.Array described below

enter image description here


arrayvals =
["00:00","04:00","09:00","11:00","12:00","14:00","17:00"];


I want to check if the time
"09:17"
or the current time is inside the array with index 2. "09:00" means 9-10 interval.

Answer

You could just check all minutes of the given values for the interval.

function check(array, value) {
    function getMinutes(s) {
        var p = s.split(':');
        return p[0] * 60 + +p[1];
    }

    var v = getMinutes(value);
    return array.some(function (a) {
        var t = getMinutes(a);
        return t <= v && v <= t + 60 || t <= v + 24 * 60 && v + 24 * 60 <= t + 60;
    });
}

var values = ["04:00", "09:00", "11:00", "12:00", "14:00", "17:00", "23:30"];

console.log(check(values, '09:17'));
console.log(check(values, '10:00'));
console.log(check(values, '13:00'));
console.log(check(values, '07:00'));
console.log(check(values, '00:15'));

Comments