Swift 是否有夏令时检查?
Is there a daylight savings check in Swift?
我需要检查当前日期是否在夏令时。在这样的伪代码中:
let date = NSDate()
if date.isDaylightSavingsTime {
print("Success")
}
我无法在 Internet 上的任何地方找到解决此问题的方法。
单独的NSDate
代表一个绝对时间点。
确定日期是否在夏令时
它需要在 时区 .
的上下文中进行解释
因此您会在 NSTimeZone
class 中找到 that method 而不是
在 NSDate
class 中。示例:
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 ... ")
}
Swift 4.0 或更高版本
您可以通过两种方式按时区查看日期 isDaylightSavingTime identifier or abbreviation。
let timeZone = TimeZone(identifier: "America/New_York")!
if timeZone.isDaylightSavingTime(for: Date()) {
print("Yes, daylight saving time at a given date")
}
let timeZone = TimeZone(abbreviation: "EST")!
if timeZone.isDaylightSavingTime(for: Date()) {
print("Yes, daylight saving time at a given date")
}
我需要检查当前日期是否在夏令时。在这样的伪代码中:
let date = NSDate()
if date.isDaylightSavingsTime {
print("Success")
}
我无法在 Internet 上的任何地方找到解决此问题的方法。
单独的NSDate
代表一个绝对时间点。
确定日期是否在夏令时
它需要在 时区 .
因此您会在 NSTimeZone
class 中找到 that method 而不是
在 NSDate
class 中。示例:
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 ... ")
}
Swift 4.0 或更高版本
您可以通过两种方式按时区查看日期 isDaylightSavingTime identifier or abbreviation。
let timeZone = TimeZone(identifier: "America/New_York")!
if timeZone.isDaylightSavingTime(for: Date()) {
print("Yes, daylight saving time at a given date")
}
let timeZone = TimeZone(abbreviation: "EST")!
if timeZone.isDaylightSavingTime(for: Date()) {
print("Yes, daylight saving time at a given date")
}