从 NSString 创建 NSDate

发布于 2025-01-01 07:13:00 字数 452 浏览 3 评论 0原文

我使用以下代码从字符串创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无力看清 2025-01-08 07:13:00

日期的 NSLog 并不是显示带有时区的日期的好方法,而是使用 NSDateFormatter 来获取所需时区的字符串。

NSDate 基于 UTC,这是可以使用 NSDateFormatter 正确显示任何时区的唯一真实时间。

来自 Apple NSDate 文档:

解析包含日期的字符串并生成字符串
日期的表示形式,您应该使用一个实例
NSDateFormatter 使用方法 dateFromString: 和 stringFromDate:
分别 - 请参阅“日期格式化程序”了解更多详细信息。

示例代码:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [df dateFromString:@"2012-01-31 01:32:30"];
NSLog(@"The date from string: %@", date);

NSString *stringFromDate = [df stringFromDate:date];
NSLog(@"stringFromDate: %@", stringFromDate);

NSLog 输出:

字符串中的日期:2012-01-31 06:32:30 +0000
字符串来自日期:2012-01-31 01:32:30

NSLog of dates is not a good way to display dates with time zones, instead use an NSDateFormatter 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 with NSDateFormatter.

From the Apple NSDate docs:

To parse strings containing dates and to generate string
representations of a date, you should use an instance of
NSDateFormatter using the methods dateFromString: and stringFromDate:
respectively—see “Date Formatters” for more details.

Example code:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [df dateFromString:@"2012-01-31 01:32:30"];
NSLog(@"The date from string: %@", date);

NSString *stringFromDate = [df stringFromDate:date];
NSLog(@"stringFromDate: %@", stringFromDate);

NSLog output:

The date from string: 2012-01-31 06:32:30 +0000
stringFromDate: 2012-01-31 01:32:30

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文