我收到两个字符串: "from"="12:30" 和 "to"="14:30" 这是两个 NSString 对象。我想检查当前时间是否在两个收到的时间之间。最好的方法是什么?谢谢。
问问题
3328 次
3 回答
3
从输入日期获取小时/分钟组件:
NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dataComps = [gregorianCal components: (NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:yourDate];
NSInteger minutes = [dateComps minute];
NSInteger hours = [dateComps hour];
然后拆分时间字符串并比较分钟和小时。另一种方法是将字符串转换为NSDate
s 并比较日期。
于 2012-09-10T09:59:43.847 回答
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);
于 2012-09-10T10:09:01.627 回答
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;
}
于 2012-09-10T09:58:38.477 回答