问题
I have the following date as NSString:
Thu May 29 14:22:40 UTC 2014
I've tried to convert it to NSDate with the following code:
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"EEE MMM d HH:mm:ss zzz yyyy";
NSDate *utc = [fmt dateFromString:@"Thu May 29 14:22:40 UTC 2014"];
NSLog(@"UTC Date:%@:", utc);
The result is nil I've tried several dateFormat regex expressions but with no luck.
What am I missing here?
回答1:
Use NSDataDetector class a subclasss of NSRegularExpression, its takes a string that of a unknown date and converts it to NSDate object if it finds a match.
NSError *error;
NSDataDetector *data = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
NSString *dateRaw = @"Thu May 29 14:22:40 UTC 2014"; // your date
NSDate *date = [data firstMatchInString:dateRaw
options:NSMatchingReportCompletion
range:NSMakeRange(0, dateRaw.length)].date;
NSLog(@"Date: %@", date);
来源:https://stackoverflow.com/questions/24739825/how-to-convert-string-date-into-nsdate-with-nsdateformatter