[英]How to convert string date into NSDate with NSDateFormatter
I have the following date as NSString: 我将以下日期作为NSString:
Thu May 29 14:22:40 UTC 2014
I've tried to convert it to NSDate with the following code: 我尝试使用以下代码将其转换为NSDate:
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. 结果为零,我尝试了几种dateFormat regex表达式,但是没有运气。
What am I missing here? 我在这里想念什么?
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. 使用NSDataDetector类是NSRegularExpression的子类,它使用日期未知的字符串,如果找到匹配项,则将其转换为NSDate对象。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.