我在Xcode中没有解决这个问题的能力:
我有这段文字:
"402加西亚01/08/15 10:26Observaciones del huésped"
我想提取我确定是 GMT +0 的日期,然后添加手机 GMT,例如 GMT +1,并在 NSString 中将该旧日期替换为新日期。
GMT 的东西我刚刚在另一个地方解决了它,所以我只需要提取并替换字符串中的日期字符串,所以我的最终结果将是这样的:
"402加西亚01/08/15 11:26Observaciones del huésped"
任何帮助将不胜感激,并提前表示感谢。
这正是NSDataDetector的目的。
我在 NSString 的一个类别中创建了一个方法:
@interface NSString (HASAdditions)
- (NSArray *)detectedDates;
@end
@implementation NSString (HASAdditions)
- (NSArray *)detectedDates {
NSError *error = nil;
NSDataDetector *dateDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
if (!dateDetector) return nil;
NSArray *matches = [dateDetector matchesInString:self options:kNilOptions range:NSMakeRange(0, self.length)];
NSMutableArray *dates = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
if (match.resultType == NSTextCheckingTypeDate) {
[dates addObject:match.date];
}
}
return dates.count ? [dates copy] : nil;
}
你可以这样称呼它:
NSArray *dates = [@"402 Garcia 01/08/15 10:26 Observaciones del huésped" detectedDates];
您可以在NSHipster上阅读有关NSDataDetector的更多信息。
这项工作始终是相同的文本结构。
NSString *text = @"402 Garcia 01/08/15 10:26 Observaciones del huésped";
// This the formatter will be use.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yy HH:mm"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
// First we extract the part of the text we need.
NSArray *array = [text componentsSeparatedByString:@" "];
NSString *dateString = [NSString stringWithFormat:@"%@ %@",[array objectAtIndex:2],[array objectAtIndex:3]];
// Here the search text
NSLog(@"%@",dateString);
// Now we use the formatter and the extracted text.
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"The date is: %@",[date description]);