Why is NSDateFormatter returning nil?

2020-02-14 20:20发布

问题:

To be more precise this is not working for me:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-ddTHH:mm:ssZ"];
NSDate *prevday = [formatter dateFromString:@"2011-04-07T22:00:48Z"];    

prevday is returning NIL.

回答1:

You need to inserts ticks in the string:

@"YYYY'-'MM'-'dd'T'HH':'mm':'ss'Z'"


回答2:

According to this document;

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html%23//apple_ref/doc/uid/TP40002369-SW1

Date formatters use the following version of the standard;

http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns

so you'd use the date format 'yyyy-MM-ddTHH:mm:ss' I'm not sure about the Z, is that supposed to be the time zone? Z in the format string will give you the 3 letter time zone name.

Edited based on your edit above:

[formatter setDateFormat:@"YYYY-MM-ddTHH:mm:ssZ"];

Is why it's returning nil.

The 'Z' expects the time zone to be in the 3 character time zone thing...

Drop the Z or escape it with a quote character. Read the tr35 doc above for more info.