0

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..!!

user2864740
  • 60,010
  • 15
  • 145
  • 220
jigs
  • 839
  • 1
  • 6
  • 23
  • 3
    Is the closing time 2 PM (in the afternoon) or 2 AM in the next morning? – Martin R Dec 07 '13 at 11:24
  • 2
    use [NSDateFormatter](https://www.google.com.kw/search?q=nsdateformatter&rlz=1C5CHFA_enKW556KW556&oq=nsdateformatter&aqs=chrome..69i57j69i59j69i60l3j69i59.2839j0j7&sourceid=chrome&espv=210&es_sm=91&ie=UTF-8)... **Upvote**, is this shock? – Fahim Parkar Dec 07 '13 at 12:09
  • 2
    **what you have tried so far?** – Fahim Parkar Dec 07 '13 at 12:09

1 Answers1

5

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
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382