Scrungepipes
Scrungepipes

Reputation: 37600

How to know what timezone to set for an NSDateFormatter when converting from an NSDate

I have a function which converts an NSString in RFC3339 to NSDate using an NSDateFormatter, but I don't know how to take account of the timezone doing the reverse.

The relevant part of the string to NSDate conversion is:

    // The result of a call to systemTimeZone is cached by the app automatically, if the user changes it that change isn't 
    // reflected unless resetSystemTimeZone is called to clear the cache.
    [NSTimeZone resetSystemTimeZone]; 
    NSLocale *enUSPOSIXLocale;
    enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [sRFC3339DateFormatter setLocale:enUSPOSIXLocale];
    if ([fromString hasSuffix:@"Z"] || [fromString hasSuffix:@"z"])
    {
        [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    }
    else 
    {
        [sRFC3339DateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    }

[sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

My question is, when converting in the other direction from an NSDate to an NSString, how do I know what to call setTimeZone with? When going from string to NSDate its by looking at the absense/presense of Z. But if I have an NSDate how do I know what time zone to set the formatter to?

Upvotes: 4

Views: 415

Answers (1)

Joel
Joel

Reputation: 16134

Your NSDate is stored as UTC/GMT timezone. So when you are converting that to a string, you pick the time zone you want the string displayed in. There is no "right" answer. It's whatever you want to display.

Upvotes: 2

Related Questions