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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3655616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:42:53  来源:igfitidea点击:

Setting an NSDate to specific date, time and timezone

iphonexcodensdateinit

提问by Structurer

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

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

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?

下面的示例代码在 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];

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

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

采纳答案by Thomas Müller

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

我想知道您是否可以在NSCalendar用于NSDateNSDateComponents. 我没有试过这个,不知道它是否会起作用,但它可能值得一试。

回答by Ben Gottlieb

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.

NDate 本身没有时区的概念。从格林威治标准时间的某个任意日期开始,它们基本上是几秒钟。因此,你不能给他们一个时区。如果时区很重要,您需要同时跟踪时间和时区。