【问题标题】:Is there a daylight savings check in Swift?斯威夫特有夏令时检查吗?
【发布时间】:2016-04-04 15:35:00
【问题描述】:

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

let date = NSDate()

if date.isDaylightSavingsTime {

    print("Success")

}

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

【问题讨论】:

标签: swift nsdate dst


【解决方案1】:

NSDate 单独代表一个绝对时间点。 决定日期是否在夏令时期间 它需要在时区的上下文中进行解释。

因此,您会在 NSTimeZone 类中找到 that method 而不是 在NSDate 类中。示例:

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 ... ?")
}

【讨论】:

    【解决方案2】:

    Swift 4.0 或更高版本

    您可以按时区identifierabbreviation 两种方式查看日期isDaylightSavingTime。

    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")     
    } 
    

    【讨论】:

      猜你喜欢
      • 2017-07-22
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 2017-11-13
      • 2015-08-19
      • 2014-09-11
      相关资源
      最近更新 更多