Writing an iPhone app in Objective-C, I have a date in string form (in UTC format, with a Z on the end to denote zero UTC offset, or zulu time), which I need to parse into an NSDate
object.
A bit of code:
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSString* str = @"2009-08-11T06:00:00.000Z";
NSDate* date = [df dateFromString:str];
Running this through the debugger, date
ends up nil
! I'm assuming it has something to do with my date format string.Z
in the date format literal, a la setting the date format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
.I've had this problem also, I'm not sure if it's a API bug within Apple's code, or my lack of understanding, but I've worked around it by using hour offsets in my date strings.
If you change the code in your example to:
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSString* str = @"2009-08-11T06:00:00.000-0700"; // NOTE -0700 is the only change
NSDate* date = [df dateFromString:str];
It will now parse the date string. Of course the -0700 hours is my offset, you'd have to change it to yours. Hope this helps.