0

I have a strings - time, start, end: format "hh:mm"

for example, "21:00". I need compare - "time" falls between the Start and End if End < Start, for example ("21:10" "10:00") should be considered as: from 'Start' to 'End' the next day.

I can't convert NSSTring like @"23:00" to NSDate, and then I need to compare... :(

Thanks for advice ;)

sch
  • 27,436
  • 3
  • 68
  • 83
Injectios
  • 2,777
  • 1
  • 30
  • 50
  • This is what NSDateFormatter is for. Or you can use NSCalendar. Of course, for your "next day" logic you need to actually do some programming. – Hot Licks Mar 18 '12 at 19:35
  • Looks right to me. What's your timezone? – Hot Licks Mar 18 '12 at 19:47
  • possible duplicate of [Convert NSString of a date to an NSDate](http://stackoverflow.com/questions/4332319/convert-nsstring-of-a-date-to-an-nsdate) – jscs Mar 18 '12 at 19:50

1 Answers1

2

You can convert a string of type HH:mm into an NSDate. If endDate is smaller than startDate, then add a day to it.

NSString *dateString = @"23:00";
NSString *startString = @"21:00";
NSString *endString = @"10:00";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"HH:mm";

NSDate *date = [formatter dateFromString:dateString];
NSDate *startDate = [formatter dateFromString:startString];
NSDate *endDate = [formatter dateFromString:endString];
if ([endDate compare:startDate] == NSOrderedAscending) {
    endDate = [endDate dateByAddingTimeInterval:24*3600];
}

if ([startDate compare:date] == NSOrderedAscending && [date compare:endDate] == NSOrderedAscending) {
    NSLog(@"Date %@ is in the interval [%@, %@]", dateString, startString, endString);
} else {
    NSLog(@"Date %@ is not in the interval [%@, %@]", dateString, startString, endString);
}

PS. I am assuming ARC is used here.

sch
  • 27,436
  • 3
  • 68
  • 83
  • I have thought about it before, but your example helps me to realize it ;) Thanks a lot – Injectios Mar 18 '12 at 19:52
  • yeap, it's correct, but I added [timeFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; to get proper NSDate from formatter – Injectios Mar 18 '12 at 19:58