NSDateFormatter dateFromString 不正确

NSDateFormatter dateFromString incorrect

我将 UITableViewCelldetailTextLabel 的值设置为当前日期,然后允许用户使用 UIDatePicker 修改该日期。我这样设置文本标签

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a MM/dd/YYYY"];
cell.detailTextLabel.text = [dateFormatter stringFromDate:currentDate];

这会正确设置文本标签,并显示类似 08:20 AM 08/07/2015 的内容。这是所需的输出。当用户选择此单元格时,我希望我的日期选择器的 date 属性 设置为单元格中显示的日期。为了实现这一点,我的 tableView:didSelectRowAtIndexPath: 方法

中包含以下内容
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a MM/dd/YYYY"];

NSString *dateString = [tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text;
self.datePicker.date = [dateFormatter dateFromString:dateString];

但是,这不是将日期设置为单元格中的日期,而是将选择器的日期设置为 08:20 AM 12/21/2014,这不应该是这样。记录 dateString 输出 table 视图单元格中的正确字符串。

我遇到这个问题有什么原因吗?

格式化程序字符串的年份部分应该是 yyyy,而不是 YYYY

而不是 @"hh:mm a MM/dd/YYYY" 格式化程序尝试使用 @"hh:mm a MM/dd/yyyy".

根据 Apple 的文档:

"A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year."

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1