Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...