【问题标题】:Date to String conversion (NSDateFormatter) doesn't work日期到字符串的转换(NSDateFormatter)不起作用
【发布时间】: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.dateNSDate,因为xcode 以2012-09-02T16:30:00Z 之类的格式输出。它应该看起来像2012-09-02 15:06:00 +0000。确保它是NSDate 对象
  • 感谢您的反馈!我会仔细检查对象,因为我可能投错了,使用:self.date = (NSDate *)[theQuestion valueForKey:@"date"];

标签: xcode sqlite


【解决方案1】:

感谢mask8 我发现这个问题与我的代码的另一部分有关。我找到this post on stackoverflow 解决了更改我通过JSON检索到的日期格式的方法。我还发现 another post on stackoverflow 描述了如何处理从字符串到 NSDate 的转换,反之亦然。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多