1

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]]);
Sven
  • 55
  • 1
  • 9
  • Use an `NSDateFormatter` to print the date in the desired format. `NSDate` objects represent absolute points in time and are independent of timezones (or anything else for that matter) – spassas Jun 30 '14 at 16:16
  • @spassas that is not true. The value of NSDate *will change* if you change the default timezone. Tested in simulator and playground. – Dan Loewenherz Mar 18 '16 at 17:42
  • @Dan "NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone" from the [NSDate reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/) – spassas Mar 20 '16 at 18:59
  • @spassas I'm not sure what that NSDate documentation reference is refuting here, but you can try it yourself. An NSDate value *will change* if you change the timezone. Of course, it doesn't *contain* timezone data, but the value of the date will change. – Dan Loewenherz Mar 21 '16 at 13:18
  • @Dan Check [this](http://stackoverflow.com/questions/24650443/nsdate-behaviour-when-saving-to-plist/24650824#24650824) for a related discussion. Logging an `NSDate` will print the _description_ of the object and the output can be quite arbitrary. – spassas Mar 21 '16 at 16:41

1 Answers1

1

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]]);
Sandy Chapman
  • 11,133
  • 3
  • 58
  • 67
  • Thank you very much, the above needs a specified dateformat, i think, otherwise the output would be empty. I add my working code above. – Sven Jul 01 '14 at 08:18
  • @Sven, I'm glad you got it working. If this is a correct answer, can you mark it as such? – Sandy Chapman Jul 02 '14 at 10:55