Swift中有夏令时支票吗?

Swift中有夏令时支票吗?

问题描述:

我需要检查当前日期是否在夏令时期间。用这样的伪代码:

I need to check to see if the current date is during daylight savings time. In pseudocode that would be like this:

let date = NSDate()

if date.isDaylightSavingsTime {

    print("Success")

}

我在互联网上的任何地方都找不到解决方案。

I haven't been able to find the solution to this anywhere on the internet.

一个 NSDate 代表绝对时间点。
要确定日期是否在夏时制期间
,需要在时区的上下文中对其进行解释。

An NSDate alone represents an absolute point in time. To decide if a date is during daylight savings time or not it needs to be interpreted in the context of a time zone.

因此,您会发现该方法位于 NSTimeZone 类中,而不是 NSDate 类。示例:

Therefore you'll find that method in the NSTimeZone class and not in the NSDate class. Example:

let date = NSDate()

let tz = NSTimeZone.localTimeZone()
if tz.isDaylightSavingTimeForDate(date) {

}






Swift 3/4的更新:

let date = Date()

let tz = TimeZone.current
if tz.isDaylightSavingTime(for: date) {
    print("Summertime, and the livin' is easy ... 🎶")
}