具有默认时区的NSDateFormatter提供的日期与NSDate描述方法不同

Luk*_*asz 9 iphone formatting date nsdate nsdateformatter

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];
Run Code Online (Sandbox Code Playgroud)

给我错误的日期格式:

日期: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.

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

Tom*_*ton 19

这是正确的行为,因为:

  1. [NSDate description]使用UTC,而不是本地时区(这就是为什么说明中有a +0000).
  2. NSDateFormatter正在使用当地时区.
  3. 您在丹麦,当地时区是Central European Time,目前UTC时长1小时.

这些匹配的唯一方法是你告诉NSDateFormatter使用UTC.但这可能不是你想要的.

  • [_dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 解决了它. (4认同)
  • 只是FTI,使用`timeZoneWithName:`代替`timeZoneWithAbbreviation:`通常会更好.对于UTC而言无关紧要,但在大多数情况下,名称是更好的选择. (3认同)