How to convert Date from JSON to NSDate

Hi I need to convert this string

"2013-12-05T08:58:55.9345456+02:00"

to NSDate I am trying next format but without luck

"yyyy-MM-dd'T'HH:mm:SSSSSSSZZZZZ"

Code below.

Can you help me with right format

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//                         "2013-12-05T08:58:55.9345456+02:00"
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:SSSSSSSZZZZZ"];

NSDate *date = [dateFormat dateFromString:jsonDateString];

Answers


Your format is close. You need:

yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZZZZ

And be sure to set the formatter's locale to en_US_POSIX. This should always be done when parsing fixed formatted, non-localized strings.


NSString * dateStr = @"2013-12-05T08:58:55.9345456+02:00";
NSArray *dateStrParts = [dateStr componentsSeparatedByString:@"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];

NSString *t = [[timePart componentsSeparatedByString:@"."] objectAtIndex:0];
NSString *newDateStr = [NSString stringWithFormat:@"%@ %@",datePart,t];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // Change here for your formated output
NSDate *date = [df dateFromString:newDateStr];
NSLog(@"%@",date);

Output

2013-12-05 08:58:55 +0000


The problem lies in the timezone where you have +02:00.

The ZZZZ only parses to +0000, hence you are getting nil.

You can do in this way:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *jsonDateString = @"2013-12-05T08:58:55.9345456+02:00";//@"2013-12-05T08:58:55.9345456+02:00"

 NSRange lastColon = [jsonDateString rangeOfString:@":" options:NSBackwardsSearch];
 if(lastColon.location != NSNotFound) {
        jsonDateString = [jsonDateString stringByReplacingCharactersInRange:lastColon withString: @""];
 }

 [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'.'SZ"];
 NSDate *date = [dateFormat dateFromString:jsonDateString];

 NSLog(@"%@",date)

EDIT:

As per rmaddy's comment, you should use SSSSS instead of single S.


Need Your Help

UTF8 character decoding in Objective C

iphone objective-c json utf-8

I am trying to parse a feed from a json webservice on my iPhone however the utf8 conversion is not working the way it should or am I doing something wrong