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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With