Peter Warbo
Peter Warbo

Reputation: 11710

Objective-C - NSTimeZone 2 hours wrong?

I'm using the following code to set my timezone to Stockholm, Europe.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Stockholm"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

NSDate *webUpdateDate = [dateFormatter dateFromString:@"2011-07-22 22:10"]; 
// Outputs "2011-07-22 20:10 +0000"

Anyone know why?

Upvotes: 0

Views: 645

Answers (1)

jscs
jscs

Reputation: 64002

I assume you're inspecting the date using NSLog. An NSDate object represents an absolute time -- it has no notion of time zone, so when it is asked for its description, it displays as if it were a time in GMT. If you want that absolute time represented for the Stockholm time zone, you need to use the date formatter again:

NSLog(@"%@", [dateFormatter stringFromDate:webUpdateDate]);

Since the date was originally created via the formatter, which already had its time zone set to Stockholm, I believe this will give you the same string that you used for input: @"2011-07-22 22:10".

Upvotes: 3

Related Questions