我收到两个字符串:“from”=“12:30”和“to”=“14:30”这两个NSString对象。 我想检查当前时间是否在两个收到的时间之间。 最好的方法是什么? 谢谢。
答案 0 :(得分:3)
从输入日期获取小时/分钟组件:
NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dataComps = [gregorianCal components: (NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:yourDate];
NSInteger minutes = [dateComps minute];
NSInteger hours = [dateComps hour];
然后拆分时间字符串并比较分钟和小时。另一种方法是将字符串转换为NSDate
并比较日期。
答案 1 :(得分:1)
Aravindhanarvi提出的第二个解决方案可能如下所示......
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);
答案 2 :(得分:0)
- (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;
}