我正在设置 UITableViewCell
的值的detailTextLabel
到当前日期,然后允许用户使用 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
输出 TableView 单元格中的正确字符串。
我遇到这个问题有什么原因吗?
最佳答案
尝试使用@“hh:mm a MM/dd/YYYY”格式化程序,而不是@“hh:mm a MM/dd/yyyy”。
根据苹果的文档:
“一个常见的错误是使用 YYYY。yyyy 指定日历年,而 YYYY 指定 ISO 年周日历中使用的年份(“一年中的周”)。在大多数情况下,yyyy 和 YYYY产生相同的数字,但它们可能不同。通常您应该使用日历年。”
关于ios - NSDateFormatter dateFromString 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31877662/