Search code examples
iossdknsdatenstimezone

setDefaultTimeZone does not work


I only found very old entries about setDefaultTimeZone in iOS SDK, but no solution for the problem, that setDefaultTimeZone simply does not do anything.

NSTimeZone *germanTimeZone = [NSTimeZone timeZoneWithName:@"Europe/Berlin"];
[NSTimeZone setDefaultTimeZone:germanTimeZone];
NSLog(@"Berlin time: %@", [[NSDate date] descriptionWithLocale:nil]);

This should result in something like:

Berlin time: 2014-06-30 15:58:34 +0200

But it results simly to:

Berlin time: 2014-06-30 15:58:34 +0000

Thank you in advance for any hint or solution.

Edit: Ok, below is my working code.

NSTimeZone *germanTimeZone = [NSTimeZone timeZoneWithName:@"Europe/Berlin"];
[NSTimeZone setDefaultTimeZone:germanTimeZone];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mma"];
NSLog(@"Time: %@", [dateFormatter stringFromDate:[NSDate date]]);

Solution

  • Try this:

    NSTimeZone* UTC = [NSTimeZone timeZoneWithName:@"UTC"];
    [NSTimeZone setDefaultTimeZone:UTC];
    

    And to print use an NSDateFormatter:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Europe/Berlin"];
    [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mma"];
    NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);