Objective-C - NSTimeZone 2 小时错误?
我使用以下代码将时区设置为欧洲斯德哥尔摩。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Stockholm"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *webUpdateDate = [dateFormatter dateFromString:@"2011-07-22 22:10"];
// Outputs "2011-07-22 20:10 +0000"
有人知道为什么吗?
I'm using the following code to set my timezone to Stockholm, Europe.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Stockholm"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *webUpdateDate = [dateFormatter dateFromString:@"2011-07-22 22:10"];
// Outputs "2011-07-22 20:10 +0000"
Anyone know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您正在使用
NSLog
检查日期。NSDate
对象表示绝对时间 - 它没有时区的概念,因此当请求它的description
时,它会显示为 GMT 时间。如果您想要代表斯德哥尔摩时区的绝对时间,则需要再次使用日期格式化程序:由于日期最初是通过格式化程序创建的,该格式化程序已经将其时区设置为斯德哥尔摩,我相信这会给您相同的结果您用于输入的字符串:
@"2011-07-22 22:10"
。I assume you're inspecting the date using
NSLog
. AnNSDate
object represents an absolute time -- it has no notion of time zone, so when it is asked for itsdescription
, it displays as if it were a time in GMT. If you want that absolute time represented for the Stockholm time zone, you need to use the date formatter again:Since the date was originally created via the formatter, which already had its time zone set to Stockholm, I believe this will give you the same string that you used for input:
@"2011-07-22 22:10"
.