使用 NSDateFormatter 时将 6 小时添加到 NSDate 对象

发布于 2025-01-01 16:34:36 字数 513 浏览 4 评论 0原文

我正在尝试格式化日期对象,并且注意到我传入的字符串;我的时间又增加了 6 个小时。这似乎将我的日期时间对象与 GMT 相关联。

我的代码:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd h:mm:ss a"];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *date = [formatter dateFromString:@"2012-02-01 03:38:12 AM"];



    NSLog(@"%@", date);

结果是:

2012-02-01 09:38:12 +0000

我已经尝试过使用和不使用 setTimeZone ,这并不重要。关于为什么显示为 GMT 时间有什么想法吗?

谢谢, 跳蚤

I am trying to format a date object and I am noticing on the string I am passing in; 6 hours is being added to my time. This seems to be associating my date time object to GMT.

My code:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd h:mm:ss a"];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *date = [formatter dateFromString:@"2012-02-01 03:38:12 AM"];



    NSLog(@"%@", date);

The result is:

2012-02-01 09:38:12 +0000

I have tried this with and without the setTimeZone and it does not matter. Any ideas on why this is displaying as GMT time?

Thanks,
Flea

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

笑着哭最痛 2025-01-08 16:34:36

格式化程序创建的日期不与任何时区相关联,而是与 NSDatedescription 方法相关联(这是 NSLog 用于输出的内容)将任何日期转换为 UTC。您必须使用另一个(或相同)日期格式化程序的 stringFromDate: 方法来使用不同的时区打印它。

The date that your formatter creates is not associated with any timezone, but the description method of NSDate (which is what NSLog uses for the output) converts any date to UTC. You would have to use another (or the same) date formatter's stringFromDate: method to print it with a different time zone.

北方的韩爷 2025-01-08 16:34:36

所有 NSDate 均为绝对时间,这意味着美国中部时间 3:00 AM 为 UTC 上午 9 点。我怀疑你的systemTimeZone是美国中部时间。

NSLog 始终显示 UTC 时间。

如果您想以字符串形式查看您所在时区的时间,那么您可以使用相同的日期格式化程序 stringFromDate: 方法,并将日期格式化程序的时区设置为该时区。

NSLog 日期格式很烦人,因为它会导致您遇到的混乱。

All NSDates are absolute times, meaning that 3:00 AM central time in the United States is 9 AM UTC. I suspect that your systemTimeZone is central time in the United States.

NSLog always shows times in UTC.

If you want to see, as a string, what the time is in your time zone, then you can use the same date formatter stringFromDate: method, and make the you set the time zone of the date formatter to that time zone.

NSLog date formatting is an annoyance because it leads to the kind of confusion you are experiencing.

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