将 NSDate 设置为特定日期、时间和时区

发布于 2024-09-17 22:42:35 字数 623 浏览 2 评论 0原文

我需要将 NSDate 设置为 iPhone 应用程序的特定日期、时间和时区。

下面的示例代码在 iOS 4 上运行良好,因为 setTimeZone 是在 iOS 4 中引入的。如何在不使用 setTimeZone 的情况下轻松将 NSDate 设置为日期、时间和时区,以便它可以在 iOS 3.0 设备上使用?

    NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:8];
[comps setDay:24];
[comps setHour:17];
[comps setMinute:5];
[comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] ];

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

我猜这应该很简单,但不知何故 NSDate、组件和日历和我不是好朋友......

I need to set a NSDate to a specific date, time and timezone for an iPhone App.

The example code below works fine on iOS 4 as the setTimeZone was introduced with iOS 4. How could I easily set a NSDate to a date, time and timezone without using setTimeZone so it can be used on iOS 3.0 devices?

    NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:8];
[comps setDay:24];
[comps setHour:17];
[comps setMinute:5];
[comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] ];

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

Guess this should be simple, but somehow NSDate, components and calendars and I are not good friends...

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

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

发布评论

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

评论(2

↙厌世 2024-09-24 22:42:35

我想知道您是否可以在用于从 NSDateComponents 创建 NSDateNSCalendar 对象上设置时区。我没有尝试过,也不知道它是否有效,但可能值得一试。

I wonder if you could set the time zone on the NSCalendar object that you use to create the NSDate from the NSDateComponents. I haven't tried this and don't know if it'll work, but it's probably worth a try.

眼眸里的快感 2024-09-24 22:42:35

NDate 本身没有时区的概念。它们基本上是自 GMT 某个任意日期以来的秒数。因此,您不能给他们一个时区。如果时区很重要,您将需要跟踪时间和时区。

NDates have no concept of time zones in and of themselves. They're basically seconds since a certain arbitrary date at GMT. As such, you can't give them a time zone. If time zone is important, you'll need to track both the time and the time zone.

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