从 NSString 创建 NSDate
我使用以下代码从字符串创建一个 NSDate
:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"The date from string: %@", [df dateFromString:@"2012-01-31 01:32:30"]);
我在结果中看到的是:
The date from string: 2012-01-31 07:32:30 +0000
这显然是不正确的。
您知道为什么我的结果日期会增加 6 个小时以及如何解决吗?
I use the following code to create an NSDate
from string:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"The date from string: %@", [df dateFromString:@"2012-01-31 01:32:30"]);
What I see in the result is:
The date from string: 2012-01-31 07:32:30 +0000
This is obviously not correct.
Do you know why it adds 6 hours to my result date and how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
日期的
NSLog
并不是显示带有时区的日期的好方法,而是使用NSDateFormatter
来获取所需时区的字符串。NSDate
基于 UTC,这是可以使用NSDateFormatter
正确显示任何时区的唯一真实时间。来自 Apple
NSDate
文档:示例代码:
NSLog 输出:
NSLog
of dates is not a good way to display dates with time zones, instead use anNSDateFormatter
to get a string for the time zone desired.NSDate
is UTC based, the one true time that can be correctly displayed for any timezone withNSDateFormatter
.From the Apple
NSDate
docs:Example code:
NSLog output: