Abbin Varghese Abbin Varghese - 3 months ago 9
Objective-C Question

Check if current time come in between two NSDate (iOS)

I'm making a simple app which retrieves information about nearby restaurants. I get all the data from an external web service. Each restaurant object has a

NSDictionary
which contains the working hours of that particular restaurant. This
NSDictionary
is structured like so..

"restaurant_working_hours" = (
{
close = {
day = 1;
dayName = Monday;
time = 0000;
};
open = {
day = 1;
dayName = Monday;
time = 1500;
};
},
{
close = {
day = 2;
dayName = Tuesday;
time = 0000;
};
open = {
day = 2;
dayName = Tuesday;
time = 1500;
};
},
{
close = {
day = 3;
dayName = Wednesday;
time = 0000;
};
open = {
day = 3;
dayName = Wednesday;
time = 1500;
};
},
{
close = {
day = 4;
dayName = Thursday;
time = 0000;
};
open = {
day = 4;
dayName = Thursday;
time = 1500;
};
},
{
close = {
day = 5;
dayName = Friday;
time = 0000;
};
open = {
day = 5;
dayName = Friday;
time = 1500;
};
}
);


In my app I need an option to find out if the restaurant is open or closed now. And also the working hours of that day in 12hr format.

I'm relatively new to development and have no idea how to approach this. I could simply run it in a loop and get all the dates but that seems inefficient.

Thank you :)

Answer

You cannot use NSDate to do the comparison. You need to:

  1. Get the current date/time (as NSDate) and extract the current time in seconds from midnight.
  2. Convert that time from the dictionaries into seconds from midnight. It's in a strange format and I am assuming, for example, that 1326 would be "26 minutes past 1PM".

1:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:(NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond)
                                      fromDate:[NSDate date]];
NSInteger nowSeconds = ([comps hour] * 60 * 24) + ([comps minutes] * 60) + [comps seconds];

2:

+ (NSInteger)dictTimeToSeconds:(NSInteger)dictTime
{
    NSInteger hours = dictTime / 100;
    NSInteger minutes = dictTime % 100;
    return (hours * 60 * 24) + (minutes * 60);
}

...

NSArray *workingHours = thatDictionary[@"restaurant_working_hours"];
for (NSDictionary *days in workingHours) {
    NSInteger openTime = [self dictTimeToSeconds:days[@"open"][@"time"]];
    NSInteger closeTime = [self dictTimeToSeconds:days[@"close"][@"time"]];
    if (openTime < nowSeconds && closeTime > nowSeconds) {
        NSLog(@"Open on day %@", days[@"open"][@"dayName"]);
    } else {
        NSLog(@"Closed on day %@", days[@"open"][@"dayName"]);
    }
}

Note: the structure of the server data is unnecessarily complicated.

Comments