6

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.

mikkola
  • 3,376
  • 1
  • 19
  • 41
swiftyboi
  • 2,965
  • 4
  • 25
  • 52
  • 1
    As `NSDate()` is a foundation class and takes, in essence, the same methods and arguments for Swift and Obj-C, the following thread should be able to help you out (obj-c): http://stackoverflow.com/questions/28438156/incorrect-time-string-with-nsdateformatter-with-daylight-saving-time . See, specifically, LeoDabus answer, which is using swift (and `NSTimeZone`) – dfrib Dec 30 '15 at 16:30
  • 1
    @dfri http://stackoverflow.com/a/27053592/2303865 – Leo Dabus Dec 30 '15 at 17:03

2 Answers2

32

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 ... ")
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

Swift 4.0 or later

You can check a date isDaylightSavingTime in two ways by time zone 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")     
} 
Elavarasan K
  • 116
  • 3