[英]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: 在我的iOS应用程序中,我有一个NSDate对象,应转换为NSString,以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
. 当我设置断点并检查
date
它正确显示为__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). 但是生成的字符串是
2015-08-25 16:03:57
,这与我当地的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
. 无论我试图以UTC / GMT格式获取字符串
2015-08-25 14:03:57
,我总是得到本地版本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
. 我在你的代码中看到的唯一奇怪的事情是你在设置
NSTimeZone
时使用dateFormatter
而不是dateTimeFormatter
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.