【问题标题】:JSON date to NSDate results to nil [duplicate]JSON日期到NSDate结果为零[重复]
【发布时间】:2014-02-24 06:28:18
【问题描述】:

我有一个 JSON 格式的日期字符串,如下所示:2014-02-07T00:00:00+08:00

我正在尝试将其转换为NSDate,格式为MM/dd/yyyy

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

NSDate *date = [dateFormat dateFromString:datestring];
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:@"MM/dd/yyyy"];

NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(@"Date: %@, formatted date: %@", date, newString);

但结果为零。怎么了?

【问题讨论】:

标签: ios json nsstring nsdate


【解决方案1】:

正确的日期格式是:

[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssxxx"];

[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

见:ICU Formatting Dates and Times

NSString *datestring = @"2014-02-07T00:00:00+08:00";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:sszzz"];
NSDate *date = [dateFormat dateFromString:datestring];
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(@"Date: %@, formatted date: %@", date, newString);

NSLog 输出:

日期:2014-02-06 16:00:00 +0000,格式化日期:02/06/2014

【讨论】:

  • 这是我正在寻找的答案。谢谢:)
猜你喜欢
  • 2010-11-17
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 2012-07-12
  • 1970-01-01
相关资源
最近更新 更多