David Casillas
David Casillas

Reputation: 1911

retaining the time zone in NSDateFormatter

I have to set a format string for a DateFormatter to convert a NSString to a NSDate.

The string is in the format: 2011-01-31 12:45:00 +0200 (y-m-d h:m:s timezone)

I'm using the format: @"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'Z" , but the timezone is converted to +0000 and the hour is adjusted, so a string like: 2011-01-31 12:45:00 +0200 is converted to: 2011-01-31 10:45:00 +0000

The Code is here:

- (NSDate *) dateForString: (NSString *)dateString
{
    NSDateFormatter *dateFormatter;
    NSLocale *enUSPOSIXLocale;
    NSDate  *date;

    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];

    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'Z"];
    // [dateFormatter  setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    date = [dateFormatter dateFromString:dateString];
    return date;
}

Upvotes: 0

Views: 358

Answers (2)

Daniel Broad
Daniel Broad

Reputation: 2522

This is absolutely expected behaviour when using NSDate - NSDate represents a moment in time so in your case the 2 date/times are equivalent.

Just make sure when you display the date using the a dateFormatter you set the timezone on the date formatter to how you want it displayed.

Upvotes: 1

Related Questions