Is there a daylight savings check in Swift?

前端 未结 2 1448
抹茶落季
抹茶落季 2020-12-18 11:18

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.isDaylightSav         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 11:49

    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.

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

    Update for Swift 3/4:

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

提交回复
热议问题