简体   繁体   English

NSDate / NSDateFormatter在iPhone iOS 4.3上返回GMT

[英]NSDate / NSDateFormatter returning GMT on iPhone iOS 4.3

Why would this code be giving me GMT? 为什么这段代码会给我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];

An NSDate represents a concrete point in time, regardless of the timezone . NSDate代表具体的时间点,与时区无关 Put another way, an NSDate does not have a timezone. 换句话说, NSDate没有时区。 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). 因此,山区时间的9:30 pm 格林尼治标准时间 3:30 am(+1天)(假设时差为6小时)。

NSDate , since it does not have a timezone, must pick one when producing a human-readable version to return as its -description . NSDate由于没有时区,因此在生成易于理解的版本时必须选择一个时区作为其-description返回。 To make things simple, it always returns a date formatted in the GMT time zone . 为简单起见, 它总是返回以GMT时区格式设置的日期 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. 如果希望将日期格式设置为其他时区,则可以设置NSDateFormatter-timezone属性,然后使用-stringFromDate:方法将日期转换为字符串。

Yes, turns out this was a bug in Apple's Numbers on the Mac. 是的,事实证明这是Mac上Apple Numbers中的错误。 Numbers was not interpreting the date string, or rather it was adding the time offset. 数字不是在解释日期字符串,而是在添加时间偏移。 The NSDate string, after formatting, was correct all along. 格式化后,NSDate字符串始终是正确的。

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

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