将小时和分钟与当前时间进行比较



我收到两个字符串:"from"="12:30"one_answers"to"="14:30",这是两个NSString对象。我想检查一下当前时间是否在收到的两个时间之间。最好的方法是什么?谢谢

从输入日期获取小时/分钟组件:

NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dataComps = [gregorianCal components: (NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:yourDate];
NSInteger minutes = [dateComps minute];
NSInteger hours = [dateComps hour];

然后拆分时间字符串并比较分钟和小时。另一种方法是将字符串转换为NSDates并比较日期。

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);
- (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;
}

相关内容

  • 没有找到相关文章

最新更新