【发布时间】:2012-09-04 02:35:09
【问题描述】:
我正在开发一个 iOS 项目,通过 JSON 从 SQLite 检索数据。该表有一个名为“日期”的日期时间列。当我在 Xcode 中检索日期并打印出结果时,我看到“2012-09-02T16:30:00Z”。但是当我尝试使用 NSDateFormatter 转换它时,结果为空。
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:formatString];
NSString *dateString = [dateFormatter stringFromDate:categoryAtIndex.date];
NSLog(@"%@ => %@", categoryAtIndex.date, dateString);
以上输出:
2012-09-02T16:30:00Z => (null)
而不是格式良好的日期字符串。
有什么想法吗?
【问题讨论】:
-
我没有答案,但有一些事情要检查:1) formatString 是否真的被分配了? 2) dateFormatter 是否被分配? 3) dateString 是否被分配?如果他们都这样做了,接下来我会尝试打印出格式字符串,如示例here 中所示。另外,尝试用
[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]替换语言环境,看看是否打印了任何内容。 -
我怀疑
categoryAtIndex.date是NSDate,因为xcode 以2012-09-02T16:30:00Z之类的格式输出。它应该看起来像2012-09-02 15:06:00 +0000。确保它是NSDate对象 -
感谢您的反馈!我会仔细检查对象,因为我可能投错了,使用:
self.date = (NSDate *)[theQuestion valueForKey:@"date"];