How to convert string date into NSDate with NSDateFormatter

喜欢而已 提交于 2019-12-08 01:04:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!