具有默认时区的 NSDateFormatter 给出的日期与 NSDate 描述方法不同 [英] NSDateFormatter with default time zone gives different date than NSDate description method

查看:40
本文介绍了具有默认时区的 NSDateFormatter 给出的日期与 NSDate 描述方法不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[_dateFormatter setDateFormat:@"dd-MM-yy HH:mm"];
NSString *dateString = [_dateFormatter stringFromDate:date];
NSLog(@"Date: %@ formatted: %@", date, dateString);
[_dateFormatter release];

给我错误的日期格式:

日期:2013-01-31 18:00:00 +0000 格式:31-01-13 19:00(来自时间戳:1359655200.000000)

在线转换工具:http://www.onlineconversion.com/unix_time.htm表示第一个日期是正确的: 2013-01-31 18:00:00 +0000.

Online conversion tool: http://www.onlineconversion.com/unix_time.htm indicates that 1st date is correct: 2013-01-31 18:00:00 +0000.

为什么 NSDateFormatter 产生与 NSLog 不同的日期?[NSDate description] 打印到控制台时不应该使用 defaultTimeZone 吗?我得到同样的错误 [_dateFormatter setTimeZone:[NSTimeZone localTimeZone]];和 [_dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

Why NSDateFormatter produces different date that NSLog? Shouldn't [NSDate description] use defaultTimeZone when printing to console? I get the same error with [_dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; and [_dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

推荐答案

这是正确的行为,因为:

This is correct behavior, because:

  1. [NSDate description] 使用 UTC,而不是本地时区(这就是为什么在描述中有 +0000 的原因).
  2. 您的 NSDateFormatter 使用的是本地时区.
  3. 您在丹麦,当地时区是欧洲中部时间,目前是 UTC 加一小时.
  1. [NSDate description] uses UTC, not the local time zone (that's why there's a +0000 in the description).
  2. Your NSDateFormatter is using the local time zone.
  3. You are in Denmark, where the local time zone is Central European Time, which is currently UTC plus one hour.

如果您告诉 NSDateFormatter 使用 UTC,这些将匹配的唯一方法.不过,这可能不是您想要的.

The only way these will match up is if you tell NSDateFormatter to use UTC. That might not be what you want, though.

这篇关于具有默认时区的 NSDateFormatter 给出的日期与 NSDate 描述方法不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆