TheLearner
TheLearner

Reputation: 19507

Formatting a date from a NSString

I am creating a NSDateCategory that formats a date but it always returns null, any ideas?

2011-06-05T16:55:00Z

+ (NSDate *)dateFromString:(NSString *)dateString
{
    NSLog(@"date string %@", dateString);

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd+hh:MM:ss"];
    NSDate *result = [dateFormatter dateFromString:dateString];
    [dateFormatter release];
    return result;
}

Upvotes: 2

Views: 878

Answers (3)

TheLearner
TheLearner

Reputation: 19507

What a huge mission! Finally figured it out. The timezone needs to be set before you even worry about the formatting!

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate *result = [dateFormatter dateFromString:dateString];
    [dateFormatter release];

Upvotes: 2

Rob Napier
Rob Napier

Reputation: 299275

Your string and your format don't match. You used a "T" in the date string to separate the time and ended with a time zone indicator. Your format uses a "+" to separate the time and has not timezone indicator. You also used "MM" for minutes, which should "mm".

See UTS#35 for the symbols used in the formatter string.

Upvotes: 2

Kai Huppmann
Kai Huppmann

Reputation: 10775

I assuem it should be dateFormatter setDateFormat:@"yyyy-MM-dd+hh:mm:ss"]; (mm is for minutes)

Upvotes: 1

Related Questions