Reputation: 2809
I receive two strings: "from"="12:30" and "to"="14:30" which are two NSString objects. I'd like to check if the current time is between the two received ones. What's the best way to do this? Thanks.
Upvotes: 3
Views: 3403
Reputation: 11834
The 2nd solution as proposed by Aravindhanarvi could look like the following ...
NSString *time1 = @"12:30";
NSString *time2 = @"14:30";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"HH:mm";
// ignore time zone of device
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date1 = [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSDate *now = [NSDate date];
BOOL inBetween = ([now compare:date1] == NSOrderedDescending
&& [now compare:date2] == NSOrderedAscending);
Upvotes: 1
Reputation: 7644
Get the hours/minutes components from the input date:
NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dataComps = [gregorianCal components: (NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:yourDate];
NSInteger minutes = [dateComps minute];
NSInteger hours = [dateComps hour];
Then split the time string and compare the minutes and hours. Another way is to convert the strings to NSDate
s and compare the dates.
Upvotes: 3
Reputation: 15628
- (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
Upvotes: 0