Saurabh Wadhwa
Saurabh Wadhwa

Reputation: 1173

NSDateFormatter Bug : incorrect string to date conversion

I have an a string in UTC which i want to convert to NSDate. Somehow Im getting 30 minutes error

The string is 2012-04-10T00:00:00+05:30

the converted date is 2012-04-09 19:00:00 +0000

where as it should have been 2012-04-09 18:30:00 +0000

Im using this function to convert string to date

- (NSDate *)parseRFC3339Date{
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

    NSDate *theDate = nil;
    NSError *error = nil; 
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:self range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", self, error);
    }

    [rfc3339TimestampFormatterWithTimeZone release];
    return theDate;
}

Upvotes: 0

Views: 271

Answers (2)

Saurabh Wadhwa
Saurabh Wadhwa

Reputation: 1173

I ran into ISOdateFormatter here http://boredzo.org/iso8601unparser/ which works perfectly. Fund it better than modifying incoming date strings.

Upvotes: 0

Ken Thomases
Ken Thomases

Reputation: 90711

If you were to create an NSRange covering the whole of the string and passed its address in to -getObjectValue:forString:range:error:, then you'd see that on output it would be short. Parsing stopped at the colon because the 'Z' in the format string only matches something like "-0800" (no colon). If you were to specify 4 Zs, 'ZZZZ', it would match something like "GMT-08:00". That allows a colon, but requires "GMT". You can try inserting the "GMT" if you're sure of the format of your date string.

Upvotes: 2

Related Questions