某些日期的NSDateformatter问题

时间:2014-04-18 07:26:22

标签: ios objective-c nsdate nsdateformatter

我的代码是

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"EDT"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:dd"];
    NSString *strDate = @"my date from backend";
    NSLog(@"value from backend %@",strDate);
    NSLog(@"after chnage by formatter %@",[dateFormatter dateFromString:strDate]);

在我的控制台中记录结果

value from backend 2014-04-18 05:01:13
after chnage by formatter 2014-04-12 23:31:00 +0000
value from backend 2014-04-18 05:01:34
after chnage by formatter (null)
value from backend 2014-04-18 05:04:27
after chnage by formatter 2014-04-26 23:34:00 +0000
value from backend 2014-04-18 05:04:47
after chnage by formatter (null)
value from backend 2014-04-18 05:05:14
after chnage by formatter 2014-04-13 23:35:00 +0000
value from backend 2014-04-18 05:05:21
after chnage by formatter 2014-04-20 23:35:00 +0000
value from backend 2014-04-18 05:08:38
after chnage by formatter (null)

为什么有些日期是空的..有谁可以帮助我?

2 个答案:

答案 0 :(得分:2)

日期格式应为:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

注意我在ss结束时更改了dd。 对于大多数情况,返回的日期是错误的。对于秒数超过30的情况,您将获得null。

答案 1 :(得分:1)

如果你需要更改时区没关系,日期格式化程序是重要的一个日期格式化程序格式相同它显示正确答案否则显示空

只需替换

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:dd"];

进入

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];