如何使用NSDateFormatter将字符串日期转换为NSDate

rav*_*n99 2 objective-c nsdate nsdateformatter ios

我有以下日期作为NSString:

Thu May 29 14:22:40 UTC 2014
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码将其转换为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);
Run Code Online (Sandbox Code Playgroud)

结果是nil 我已经尝试了几个dateFormat正则表达式但没有运气.

我在这里错过了什么?

Sha*_*med 5

使用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);
Run Code Online (Sandbox Code Playgroud)