为什么 NSCalendar 的 dateFromComponents 返回错误的日期?

发布于 2024-10-04 23:58:01 字数 484 浏览 0 评论 0原文

我期待 2010-10-11 00:00:00

但我收到 2010-10-10 21:00:00 +0000

我知道,我可以添加几个小时并收到所需的日期,但我不明白为什么我得到前一天的 21 小时...

请帮忙!

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:10];
[comps setDay:11];

[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *retDate = [cal dateFromComponents:comps];

I am expecting 2010-10-11 00:00:00

But instead I receive 2010-10-10 21:00:00 +0000

I know, that I can add a few hours and receive desired date, but I do not understand why I get previous day with 21 hours...

Please, help!

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:10];
[comps setDay:11];

[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *retDate = [cal dateFromComponents:comps];

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

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

发布评论

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

评论(2

美男兮 2024-10-11 23:58:01

我认为您的问题可以通过设置 NSTimeZone 来解决。

I think your problem may be solved by setting the NSTimeZone.

温柔女人霸气范 2024-10-11 23:58:01

如果您需要特定的时间格式,请使用该格式化程序,或者编写此格式以获得正确的时间。第一个选项...

let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let localDate = formatter.dateFromString("1989-10-17T05:00:00.000-0000")

或者如果您需要组件中的日期,请使用以下代码,例如...

let calendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "GMT")!
    let date = calendar.dateFromComponents(components)

或者您需要

If you need a specific time format use that formatter or else write this to get correct time. first option...

let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let localDate = formatter.dateFromString("1989-10-17T05:00:00.000-0000")

or if you need date from components use the below code like ...

let calendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "GMT")!
    let date = calendar.dateFromComponents(components)

or you need

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