NSDate / NSDateFormatter returning GMT on iPhone iOS 4.3

人走茶凉 提交于 2019-12-04 05:29:07

问题


Why would this code be giving me GMT? (I am in US Mountain Time)

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];     

NSDate *now = [NSDate date];
NSString *storeTime = [dateFormatter stringFromDate:now];

回答1:


An NSDate represents a concrete point in time, regardless of the timezone. Put another way, an NSDate does not have a timezone. Timezones are only relevant when you want to display the date to the user. So 9:30pm in Mountain Time is 3:30am (+1 day) in GMT (assuming a 6 hour time difference).

NSDate, since it does not have a timezone, must pick one when producing a human-readable version to return as its -description. To make things simple, it always returns a date formatted in the GMT time zone. If you would like the date formatted to be in a different timezone, you can set the -timezone property of an NSDateFormatter, and then convert the date into a string using the -stringFromDate: method.




回答2:


Yes, turns out this was a bug in Apple's Numbers on the Mac. Numbers was not interpreting the date string, or rather it was adding the time offset. The NSDate string, after formatting, was correct all along.



来源:https://stackoverflow.com/questions/7199807/nsdate-nsdateformatter-returning-gmt-on-iphone-ios-4-3

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