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

浪尽此生 提交于 2019-11-30 08:22:34

问题


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)

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

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:


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).
  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.

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




回答2:


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. The converter you have used gives you GMT time.

If you want time specific timezone and you know the offset from GMT you can use the following,

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

Hope this solves the problem.



来源:https://stackoverflow.com/questions/16717793/nsdateformatter-with-default-time-zone-gives-different-date-than-nsdate-descript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!