ios - NSDateFormatter dateFromString 不正确

标签 ios nsdate uidatepicker

我正在设置 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产生相同的数字,但它们可能不同。通常您应该使用日历年。”

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

关于ios - NSDateFormatter dateFromString 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31877662/

相关文章:

ios - 如何在 IOS 的 UI slider 中添加不同的颜色?

ios - 使用 AFNetworking 下载时泄漏

ios - 将持续数天的 NSDate 拆分为几个跨度

ios - Objective-C:像 2014-02-02T20:55:31.555Z 这样的日期的日期格式是什么

ios - iOS 中的日期选择器

ios - 在UIDatePicker中设置今天的日期而非设备日期

jQuery UI 日期选择器样式损坏

ios - 如何快速比较颜色

ios - 如何启用苹果应用商店中的应用程序以在浏览器上查看?

iphone - 如何按天对 NSDate 对象进行分组?