如何扫描这个特定的字符串?

时间:2014-01-23 14:36:11

标签: objective-c

假设我有一个这样的字符串:01/22/2014 09:00 pm GMT

如何才能获得时间:09:00 pm

这是我的代码

NSString *stringValue=[[NSString alloc]initWithFormat:@"%@",[dataForLoading valueForKey:@"realtime_time"]];

NSLog(@"String Value:%@",stringValue);

NSScanner *scanner=[NSScanner scannerWithString:stringValue];

2 个答案:

答案 0 :(得分:1)

你走了:

NSString *input = @"01/22/2014 09:00 pm GMT";
NSDateFormatter *dateFormatterInput = [[NSDateFormatter alloc] init];
[dateFormatterInput setDateFormat:@"MM/dd/yyyy hh:mm a Z"];
NSDate *date = [dateFormatterInput dateFromString:input];
NSDateFormatter *dateFormatterOutput = [[NSDateFormatter alloc] init];
[dateFormatterOutput setDateFormat:@"hh:mm a"];
NSString *output = [dateFormatterOutput stringFromDate:date];

NSLog(@"Output: %@", output);

答案 1 :(得分:0)

arturgrigor解决方案的一个小改进是不会分配/初始化另一个NSDateFormatter,因为它们非常昂贵,因此你应该避免使用超过你需要的东西。

NSString *input = @"01/22/2014 09:00 pm GMT";
NSDateFormatter *dateFormatterInput = [[NSDateFormatter alloc] init];
[dateFormatterInput setDateFormat:@"MM/dd/yyyy hh:mm a Z"];
NSDate *date = [dateFormatterInput dateFromString:input];
[dateFormatterInput setDateFormat:@"hh:mm a"];
NSLog(@"%@", [dateFormatterInput stringFromDate:date]);