my code is

    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]);

log result in my console

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)

why some dates are null..can anyone please help me ?

有帮助吗?

解决方案

The date format should be:

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

Notice I changed the dd at the end for ss. For most of the cases the date returned was wrong. For those cases where seconds were more than 30, you get null.

其他提示

if you need to change the time zone does not a matter, the date formatter is the important one both date formatter format are equal it show the correct answer otherwise it shows the null

just replace the line

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

into

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top