问题
I don't have the ability in Xcode to resolve this problem:
I have this text:
"402 Garcia 01/08/15 10:26 Observaciones del huésped"
And i want to extract the date that i'm sure is GMT +0, then add the phone GMT for example GMT +1 and the replace that old date with the new date inside the NSString.
The GMT stuff i have just solve it in another place so i just need to extract and replace the date string in to the string so my final result will be something like:
"402 Garcia 01/08/15 11:26 Observaciones del huésped"
Any help will be appreciated and thanks in advance.
回答1:
That is exactly what NSDataDetector is there for.
I made a method in a category on 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;
}
You can just call it like this:
NSArray *dates = [@"402 Garcia 01/08/15 10:26 Observaciones del huésped" detectedDates];
You can read more about NSDataDetector over on NSHipster
回答2:
This work is alway is the same text structure.
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]);
来源:https://stackoverflow.com/questions/27861182/extract-a-date-from-a-complex-nsstring