Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

nsdate - Is there a daylight savings check in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...