objective-c - 如何创建将处于 DST 模式的 NSDate

标签 objective-c swift nsdate

我想知道如何创建将处于 DST 模式的 NSDate。

我正在使用方法nextDaylightSavingTimeTransition

这是来自文档:

This property contains the date of the next (after the current instant) daylight saving time transition for the receiver. Depending on the time zone of the receiver, the value of this property may represent a change of the time zone's offset from GMT. Returns nil if the time zone of the receiver does not currently observe daylight saving time.

然后我验证它是否处于 DST 模式:

我正在使用方法:isDaylightSavingTimeForDate:

这是来自文档:

YES if the receiver uses daylight saving time at aDate, otherwise NO.

代码:

NSDate *nextDstTransition = [[NSTimeZone localTimeZone] nextDaylightSavingTimeTransition];


BOOL isDstOnForOldDate = [[NSTimeZone localTimeZone] isDaylightSavingTimeForDate:nextDstTransition];

很遗憾,我的 nextDstTransition 不在夏令时。我的假设与时区问题有关。

您能否分享有关在 DST 模式下创建 NSDate 的选项。

最佳答案

如果您仔细阅读文档:nextDaylightSavingTimeTransition:返回 DST 在给定日期之后更改的下一次时间,如果您处于 DST 从不更改(始终打开或始终关闭)的时区,则返回 nil。如果您的日期是夏令时,那么您就可以了,否则您需要知道它何时更改。

NSDate* date = ...
if (! [[NSTimeZone localTimeZone] isDaylightSavingTimeForDate:date]) {
    NSDate* change = [[NSTimeZone localTimeZone] nextDaylightSavingTimeTransitionAfterDate:date];
    if (change != nil) {
        date = change;
    } else {
        // Tough, there is no DST in this time zone. 
    }
}

关于objective-c - 如何创建将处于 DST 模式的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39250516/

相关文章:

ios - objective-c presentViewController 位置

ios - 从远程通知获取在后台运行的方法

ios - 如何以编程方式从 UIViewController 转到 UITableViewController

ios - 单击表格 View 单元格时转到另一个 View

objective-c - 如何在 NSDate 上设置时间?

objective-c - 如何单击 nstableview 中的复选框并使用 KVC 更新对象?

iphone 6 的 iOS 背景图片

ios - NSURLConnection:与调用 connection:didReceiveResponse: 和 connection:didFailWithError: 的顺序混淆

ios - 在 Swift 中使用 NSDate 组件

iphone - 在 iOS 上查找当前日期之前的星期一