snowflakes74 snowflakes74 - 23 days ago 4
AngularJS Question

How to check selected time is within the given time range in Javascript

I need to determine if the selected times (start time, end time) by the user is in the array of appointment times.

I get the appointment times from exchange web service and the output is :

[{Status: "Busy", StartTime: "2016-10-05T11:00:00+10:00", EndTime: "2016-10-05T11:30:00+10:00"},{Status: "Busy", StartTime: "2016-10-05T13:00:00+10:00", EndTime: "2016-10-05T15:30:00+10:00"}]

The times that user has selected are :

var start_time = Date.parse("2016-10-05T14:30");
var end_time = Date.parse("2016-10-05T15:00");

So far I have tried the following but I am not sure if this is the correct way to do it:

var data = [{Status: "Busy", StartTime: "2016-10-05T11:00:00+10:00", EndTime: "2016-10-05T11:30:00+10:00"},{Status: "Busy", StartTime: "2016-10-05T13:00:00+10:00", EndTime: "2016-10-05T15:30:00+10:00"}];

for (var key in data)
var obj = data[key];
if (obj['Status'] == 'Busy')
check_open_time_val = Date.parse(obj['StartTime']);
check_close_time_val = Date.parse(obj['EndTime']);

if (check_open_time_val > open_time)
console.log('Is Busy');
// break;
return true;
}else {
console.log(obj['Status'] + 'XXXXX');

How do I check if the start_time and the endtime are not in any of the appointment times.


You can combine this logic with Array.prototype.some

let data = [{Status: "Busy", StartTime: "2016-10-05T11:00:00+10:00", EndTime: "2016-10-05T11:30:00+10:00"},{Status: "Busy", StartTime: "2016-10-05T13:00:00+10:00", EndTime: "2016-10-05T15:30:00+10:00"}],
    start_time = Date.parse("2016-10-05T14:30:00+10:00"),
    end_time = Date.parse("2016-10-05T15:00:00+10:00");

let isClash = data.some(obj => {
    let s = Date.parse(obj.StartTime), e = Date.parse(obj.EndTime);

    return obj.Status === 'Busy' && start_time <= e && end_time >= s;

console.log('is clash?', isClash);

Note that I aligned the UTC offsets of your start_time and end_time so you could see that it works :)