Dr Nic
Dr Nic

Reputation: 2182

Parsing unsupported date formats in via Cocoa's NSDate

With the Cocoa framework how can I parse @"2008-12-29T00:27:42-08:00" into an NSDate object? The standard -dateWithString: doesn't like it.

Upvotes: 13

Views: 7867

Answers (4)

Jorge Perez
Jorge Perez

Reputation: 1606

How the time zone is set changed from ios 5 to ios 6. iOS 6 supports the format +01:00 using ZZZZZ but ios 5 doesn't. I solved this issue with this solution which worked for me to parse a date with the following format in ios 5 and 6.

2013-05-07T00:00:00+01:00

NSMutableString *newDate = [date mutableCopy];
NSRange range;
range.location = 22;
range.length = 1;
[newDate replaceCharactersInRange:range withString:@""];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZ"];    
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:newDate];

Upvotes: 1

mfazekas
mfazekas

Reputation: 5699

You can use NSDateFormatter to parse dates:

    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    date = [dateFormatter dateFromString:dateStr];

The unicode date format patterns defines the format string you can use with the setDateFormat: method.

Note that if you're targeting 10.4 then you need to call: [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];. Not needed for iphone, or leopard as this mode is the default there.

Upvotes: 31

DenNukem
DenNukem

Reputation: 8254

Actually, you need to set timezone, calendar and locale. If you don't set locale, an user has AM/PM time enabled the formatter will add AM/PM marker! If you don't set the timezone, it will use the current timezone, but will mark it as "Z" ("Zulu" or GMT). If you do not set calendar, users with Japanese Imperial calendar will have number of years since current Emperor's ascension instead of the number of years since Jesus Christ was born. Be sure to test in all of the scenarios I mentioned!

    NSDateFormatter * f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    f.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    f.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    f.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
    NSString * str = [f stringFromDate:someDate];
    NSDate * date = [f dateFromString:dateStr];

Upvotes: 6

Peter Hosey
Peter Hosey

Reputation: 96323

If you only need to handle the ISO 8601 format (of which that string is an example), you might try my ISO 8601 parser and unparser.

Upvotes: 6

Related Questions