如果超过30分钟,如何将NSString时间转换为条件

时间:2013-08-14 18:20:17

标签: ios nsstring nsdate

我有一个提取的NSString 00:50,如果它超过或少于30分钟我需要调整。

3 个答案:

答案 0 :(得分:3)

如果字符串具有固定格式 HH:MM,那么您只需比较字符串:

NSString *timeStr = ...; // time in HH:MM format
if ([timeStr compare:@"00:30"] == NSOrderedAscending) {
    // less than 30 minutes
} else {
    // 30 minutes or more
}

答案 1 :(得分:2)

你在这里

NSString *string = @"00:50";
NSArray *components = [string componentsSeparatedByString:@":"];

int hours = [[components objectAtIndex:0] intValue];
int minutes = [[components objectAtIndex:1] intValue];

if( ((hours * 60) + minutes) > 30) {
     // ...
}

答案 2 :(得分:2)

您要找的是NSDateFormatter

NSString *time = @"00:50";
NSDateFormatter *timeConverter = [NSDateFormatter new];
[timeConverter setDateFormat:@"HH:mm"];

NSDate *date = [timeConverter dateFromString:time];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
NSInteger hours = [components hour];
NSInteger minutes = [components minute];
NSInteger seconds = [components second];

if (minutes + (hours * 60) > 30) {

    // Do your thing here.
}

从那里,您可以拥有任何时间或日期,并从中提取您需要的任何内容,只需将您需要的组件添加到NSDateComponents对象。

以下是您可以从NSDate对象中提取的所有内容: http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSDateComponents_Class/Reference/Reference.html