Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter stringFromDate: returning local time instead of UTC / GMT

inside my iOS App I have an NSDate Object that should be converted to a NSString showing date and time in UTC / GMT:

NSDateFormatter * dateTimeFormatter = [[NSDateFormatter alloc] init];
[dateTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
// OR  [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// OR  [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
// OR  [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
// OR  [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// OR  not specify the TimeZone at all...

NSString *result = [dateTimeFormatter stringFromDate:date];

When I set a breakpoint and examine date it is correctly displayed as __NSDate * 2015-08-25 14:03:57 UTC. However the resulting string is 2015-08-25 16:03:57, which is the same date in my local TimeZone (CEST).

No matter which solution I tried to get a string in UTC /GMT format 2015-08-25 14:03:57, I always get the local version 2015-08-25 16:03:57.

All sources I found state, that this should work. Where is my mistake?

like image 929
Andrei Herford Avatar asked Mar 14 '23 23:03

Andrei Herford


1 Answers

This code should works:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];

NSDate *now = [NSDate date];
NSString *dateAsString = [formatter stringFromDate:now];

The only strange thing I see in your code it's that you use dateFormatter instead of dateTimeFormatter when set the NSTimeZone.

like image 102
Massimo Polimeni Avatar answered May 07 '23 21:05

Massimo Polimeni