How can I convert a NSString representation of a time value into two NSInteger's containing the hour and minute?

社会主义新天地 提交于 2019-12-01 01:14:08
NSScanner* timeScanner=[NSScanner scannerWithString:...the time string...];
int hours,minutes;
[timeScanner scanInt:&hours];
[timeScanner scanString:@":" intoString:nil]; //jump over :
[timeScanner scanInt:&minutes];

NSLog(@"hours:%d minutes:%d",hours,minutes);
  1. Use an NSDateFormatter to convert your string into an NSDate.
  2. Use the [NSCalendar currentCalendar] to extract various date components (like the hour, minute, etc).

In other words:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"h:m a"];
NSDate *date = [formatter dateFromString:@"12:59 pm"];
[formatter release];

NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSLog(@"hour: %d", [components hour]);
NSLog(@"minute: %d", [components minute]);

This is the official way, as I know it. It's not pretty:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
[dateFormatter setDateFormat:@"h:m a"];
NSDate *date = [dateFormatter dateFromString:@"12:34 am"];

[dateFormatter setDateFormat:@"h"];
NSString *hours = [dateFormatter stringFromDate:date];

[dateFormatter setDateFormat:@"m"];
NSString *minutes = [dateFormatter stringFromDate:date];

BUT the string fiddling way of doing it (look for :, look for space, ...), may give you more headaches on the long term.

NSString *time = @"1:00 am";
NSString *removeam = [time stringByReplacingOccurencesOfString:@" am" withString:@""];
SString *removepm = [removeam stringByReplacingOccurencesOfString:@" pm" withString:@""];   
NSArray *timeArray = [removepm componentsSeparatedByString:@":"];
NSInteger *hour = [[timeArray objectAtIndex:0] intValue];
NSInteger *mins = [[timeArray objectAtIndex:1] intValue];

If you're building an alarm clock app, you probably will want to look into the NSDate and NSDateFormatter classes, instead of trying to pull all those strings apart into integer types. Also, your time range is a bit weird (maybe a typo?) - don't you want all 24 hours to be available?

Mohit tomar

get the time interval and write it as

duration.text = [NSString stringWithFormat:@"%d:%02d", (int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60, nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!