Reputation: 8608
I am trying to convert a string that looks like this (not sure if that fully correct RFC3339 format):
2014-07-07T16:11:02.085Z
To an NSDate. I've looked around and have tried multiple formats and am using code from Apple on converting around. Here is the formats I've been trying:
@"yyyy'-'MM'-'dd'T'HH':'mm':'sss'Z'" //apples
@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"
@"yyyy-MM-dd'T'HH:mm:ss.sss'Z'"
@"yyyy-MM-dd'T'HH:mm:ss"
How I'm going about it:
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:@"2014-07-07T16:11:02.085Z"];
NSLog(@"date: = %@", date);
NSString *userVisibleDateTimeString;
if (date != nil) {
// Convert the date object to a user-visible date string.
NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
NSLog(@"userVisibleDateTimeString = '%@'", userVisibleDateTimeString);
Upvotes: 1
Views: 1761
Reputation: 539725
Your third try is almost correct. The date format should be
@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
with capital "S" for "fractional seconds".
Upvotes: 4