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

查看:143
本文介绍了具有默认时区的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]];

推荐答案

是正确的行为,因为:


  1. [NSDate描述] 使用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天全站免登陆