NSDate / NSDateFormatter 在 iPhone iOS 4.3 上返回 GMT
为什么这段代码会给我 GMT? (我现在是美国山区时间)
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];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSDate
表示一个具体的时间点,与时区无关。换句话说,NSDate
没有时区。仅当您想向用户显示日期时,时区才相关。因此,山地时间的晚上 9:30 是格林尼治标准时间 (GMT) 的凌晨 3:30(+1 天)(假设有 6 小时时差)。NSDate
由于它没有时区,因此在生成人类可读版本时必须选择一个时区作为其-description
返回。为简单起见,它始终返回采用 GMT 时区格式的日期。如果您希望日期格式化为不同的时区,可以设置NSDateFormatter
的-timezone
属性,然后使用-timezone
将日期转换为字符串code>-stringFromDate: 方法。An
NSDate
represents a concrete point in time, regardless of the timezone. Put another way, anNSDate
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 anNSDateFormatter
, and then convert the date into a string using the-stringFromDate:
method.是的,事实证明这是 Mac 上 Apple Numbers 中的一个错误。 Numbers 没有解释日期字符串,或者更确切地说,它添加了时间偏移量。 NSDate 字符串在格式化后始终是正确的。
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.