Serge
Serge

Reputation: 2129

Converting JSON string to NSDate occurs an error

Here is a json string value I receive need to convert to NSDate:

2017-04-08T13:51:00.000+03:00

And here is I convert to NSDate:

+ (NSDate *)stringDateToDate:(NSString *)aStringDate
{
    NSDate *date = nil;

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss:SSS"];

    date = [dateFormat dateFromString:aStringDate];
    NSLog(@"nsdate: %@", date);

    return date;
}

As result it logs:

nsdate: (null)

Seems that date format is incorrect. How to fix that issue?

Upvotes: 0

Views: 67

Answers (2)

luk2302
luk2302

Reputation: 57124

Use the following date formatter string

"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"

which uses ZZZZZ for the timezone / zone / time offset - e.g. +03:00
SSS for the fractional seconds - e.g. 123
and most importantly uses . between the seconds and its fractions instead of :

Thanks to rmaddy for correcting the number of S and Z to meet the exact required input

Note that you can get away with using SZ instead of SSSZZZZZ because the parser is smart enough to parse it anyway. If you want to create a string from a date however you need the above date formatter string.

"yyyy-MM-dd'T'HH:mm:ss.SZ"

enter image description here

More details on date formatter strings can be found in the unicode section for
Date Format Patterns

Upvotes: 2

Bryan Hadlock
Bryan Hadlock

Reputation: 2716

Z at the end for the time offset

+ (NSDate *)stringDateToDate:(NSString *)aStringDate
{
   NSDate *date = nil;

   NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
   [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss:SSSZ"];

   date = [dateFormat dateFromString:aStringDate];
   NSLog(@"nsdate: %@", date);

   return date;
}

Upvotes: -1

Related Questions