I ask a database for the date of an object. I get back a string as such: 2011-08-16T19:03:21.000Z (Here’s another one: 2011-08-12T02:13:16.000Z);
Edit: Here is another one that I made August 16th, 2011, at 12:51 PM for testing purposes: 2011-08-16T19:51:24.000Z
I want to convert this date to another format for display purposes. This format may change in the future, so I don’t want to do direct string manipulation. The best thing to do is turn it into an NSDate, and then back to the correctly formatted string. However, I cannot, for the life of me, get the darn string into an NSDate.
- (NSString *)makeDateStringReadable:(NSString *)dateString {
NSLog(@"The String: %@", dateString);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss.zzzz"];
NSDate *theDate = [formatter dateFromString:dateString];
NSLog(@"The Date: %@", theDate);
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *finalString = [formatter stringFromDate:theDate];
[formatter release];
return finalString;
}
The original string is passed in, and is logged out, but the “The Date:” log always shows null. I’m assuming the format is not correct… but I can’t get it to be correct. I’ve tried using this as a reference as well.
Can I get the aid of a DateFormatter guru? Thank you so much!
One problem (but possibly not the problem) is that that
zzzzis not the right specification for000Z. The end of the RFC 3339 timestamp is not a four-character timezone specification, but fractional seconds plus a literal "Z". So try changingzzzztoSSS'Z'.