ios8 Timezone parsing changed?

64 Views Asked by At

Has the parsing for timzones changed in iOS8?

I try to parse the date "2014-09-03 12:20:38.000 +0200"

with this code and get nil:

-(NSDateFormatter*) dateAndTimeFormatter{
    if(!_dateAndTimeFormatter){
        _dateAndTimeFormatter = [[NSDateFormatter alloc]init];
        [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZZZ"];
        _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle;
        _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle;
    }
    return _dateAndTimeFormatter;
}

alternatively

[_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS Z"]; 

doesn't work either.

2

There are 2 best solutions below

1
On BEST ANSWER

Setting dateStyle or timeStyle will override any custom dateFormat you have set. Your date string does not conform in any way to NSDateFormatterShortStyle, which is why you are getting nil when trying to convert strings to dates.

Furthermore, according to Unicode Technical Standard #35 revision 31, the timezone specifier of "ZZZZZ" corresponds to date strings with formats like "-08:00" or "-07:52:58", not "+0200" as you have in your example. One of the specifiers that matches "+0200" is the one with one to three capital "Z" characters.

This should work for you:

- (NSDateFormatter *)dateAndTimeFormatter {
    if (!_dateAndTimeFormatter) {
        _dateAndTimeFormatter = [[NSDateFormatter alloc] init];
        [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZ"];
    }
    return _dateAndTimeFormatter;
}

Also, note that your code should also not be working prior to iOS 8.

2
On

The first thing I would try is to reset your time settings in XCode: settings -> general -> date time -> time format (either set to 24 hour or reset the selection).

If that does not work, here is a guide to overwrite the locale which is basically:
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];