1

我正在使用NSDateFormatter将当前日期转换为字符串(格式为:)February 16, 2013。如何将此字符串转换回NSDate对象?

NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterLongStyle timeStyle:NSDateFormatterNoStyle];

问题似乎是写出了月份(Februaryvs. 02),而其他问题仅解释使用NSDateFormatter诸如 之类的格式MM-dd-yyyy,我认为这在这里是不可能的。我必须手动解析此日期,转换February02,然后从那里开始吗?

4

3 回答 3

4

您可以使用相同 NSDateFormatter 类的 dateFromString 来执行反向转换。要使其工作,您需要定义 dateStyle,以便解析器知道应该如何解析文本字符串。对于您提供的日期样式,下面的代码将起作用:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSDate *date = [dateFormatter dateFromString:@"February 16, 2013"];

NSLog(@"%@", date);
于 2013-02-17T02:52:11.920 回答
1

如果您希望能够使用本地化的日期格式,您应该使用模板

 NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                       dateStyle:NSDateFormatterLongStyle
                                                       timeStyle:NSDateFormatterNoStyle];

NSLog(@"%@", dateString);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"MMMdY"
                                                             options:0
                                                              locale:[NSLocale currentLocale]]];

NSLog(@"%@", [dateFormatter dateFromString:dateString]);
于 2013-02-17T03:00:46.153 回答
1

Since you have a fixed format that you wish to parse, you must setup the date formatter with the locale of en_US_POSIX. Then you must set he date format to MMMM dd, yyyy. This will pare any date string that has the full month name, the month day, a comma, then the four-digit year.

于 2013-02-17T03:42:14.553 回答