简体   繁体   English

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

[英]NSDateFormatter with default time zone gives different date than NSDate description method

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];

Gives me wrong date formatted: 给我错误的日期格式:

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

Online conversion tool: http://www.onlineconversion.com/unix_time.htm indicates that 1st date is correct: 2013-01-31 18:00:00 +0000. 在线转换工具: http ://www.onlineconversion.com/unix_time.htm表示第一个日期是正确的:2013-01-31 18:00:00 +0000。

Why NSDateFormatter produces different date that NSLog? 为什么NSDateFormatter会生成与NSLog不同的日期? Shouldn't [NSDate description] use defaultTimeZone when printing to console? 打印到控制台时, [NSDate description]不应该使用defaultTimeZone吗? I get the same error with [_dateFormatter setTimeZone:[NSTimeZone localTimeZone]] ; 我用[_dateFormatter setTimeZone:[NSTimeZone localTimeZone]]得到了同样的错误; and [_dateFormatter setTimeZone:[NSTimeZone systemTimeZone]] ; [_dateFormatter setTimeZone:[NSTimeZone systemTimeZone]] ;

This is correct behavior, because: 这是正确的行为,因为:

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

The only way these will match up is if you tell NSDateFormatter to use UTC. 这些匹配的唯一方法是告诉NSDateFormatter使用UTC。 That might not be what you want, though. 但这可能不是你想要的。

It is the timezone problem as you discovered. 这是您发现的时区问题。 Default time zone takes the system timezone. 默认时区采用系统时区。 Say, if you are in GMT+1, you are supposed to get 19-00. 比如,如果你在GMT + 1,你应该得到19-00。 The converter you have used gives you GMT time. 您使用的转换器为您提供GMT时间。

If you want time specific timezone and you know the offset from GMT you can use the following, 如果你想要时间特定的时区并且你知道GMT的偏移,你可以使用以下方法,

    [_dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:2*60*60]];//GMT+2.0

Hope this solves the problem. 希望这能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM