Compare current time with two times-of-day strings

983 views Asked by At

How can i get time like "11:30" formate so that i want to compare it with the following:

strOpenTime = @"10:00";
strCloseTime = @"2:00";

so how can i get current time like as above open/close time format and i want if the current time is inside the interval open/close time?

Thanks in advance..!!

1

There are 1 answers

0
Martin R On BEST ANSWER

First you have to convert the strings "10:00", "2:00" to a date from the current day. This can be done e.g. with the following method (error checking omitted for brevity):

- (NSDate *)todaysDateFromString:(NSString *)time
{
    // Split hour/minute into separate strings:
    NSArray *array = [time componentsSeparatedByString:@":"];

    // Get year/month/day from today:
    NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];

    // Set hour/minute from the given input:
    [comp setHour:[array[0] integerValue]];
    [comp setMinute:[array[1] integerValue]];

    return [cal dateFromComponents:comp];
}

Then convert your open and closing time:

NSString *strOpenTime = @"10:00";
NSString *strCloseTime = @"2:00";

NSDate *openTime = [self todaysDateFromString:strOpenTime];
NSDate *closeTime = [self todaysDateFromString:strCloseTime];

Now you have to consider that the closing time might be on the next day:

if ([closeTime compare:openTime] != NSOrderedDescending) {
    // closeTime is less than or equal to openTime, so add one day:
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comp = [[NSDateComponents alloc] init];
    [comp setDay:1];
    closeTime = [cal dateByAddingComponents:comp toDate:closeTime options:0];
}

And then you can proceed as @visualication said in his answer:

NSDate *now = [NSDate date];

if ([now compare:openTime] != NSOrderedAscending &&
    [now compare:closeTime] != NSOrderedDescending) {
    // now should be inside = Open
} else {
    // now is outside = Close
}