Is there a daylight savings check in Swift?
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 ... )
}
How to get daylight saving time with using pod TimeZoneLocate in Swift
An interesting thing I noted: TimeZone.current
is returning the correct time zone, but location?.timeZone
is not returning the correct time zone. If there is a way to implement TimeZone.current, i.e. the application will always be using the user's current location, then I would advise using that. If users can enter a custom location, however, then you need to get a workaround for the apparent incorrect time zone returned by location?.timeZone
.
My workaround is as follows. Notice that we manually adjust the location of the time zone we want by changing the .secondsFromGMT()
property. This is how I adjusted your code, and it was returning the correct time zone for my personal location.
extension String {
func UTCToLocal(incomingFormat: String, outgoingFormat: String, location: CLLocation?) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: self)
var timeZone = location?.timeZone ?? TimeZone.current
if timeZone.isDaylightSavingTime() {
timeZone = TimeZone(secondsFromGMT: timeZone.secondsFromGMT() - 7200)!
}
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = outgoingFormat
let output = dateFormatter.string(from: dt ?? Date())
return output
}
}
NOTE:
Time zones are very complex and change from place to place and from the current time of year. Just because this workaround works for my current location on this current day, doesn't mean that this workaround always works. However, you can look at the timeZone.isDaylightSavingTime()
value returned as well as the current location to create a new time zone via timeZone = TimeZone(secondsFromGMT: timeZone.secondsFromGMT() - x
as needed. This is the way you can implement the
"I thought about using function isDaylightSavingTime() with if statement, but I can't figure out where to add this one hour."
idea that you had.
EDIT:
For the record, the time zone I was using was CST, or Chicago time. The date I wrote this code at was April 19, 2019.
Swift: Date parsing on daylight saving time
You just need to set your date formatter's calendar property. This will also avoid using the user device's calendar which might result in parsing the wrong year. Don't forget to always set your date formatter's locale to "en_US_POSIX" when parsing a fixed date format:
extension String {
func date(using format: String) -> Date? {
let df = DateFormatter()
df.calendar = .init(identifier: .iso8601)
df.locale = .init(identifier: "en_US_POSIX")
df.timeZone = .current
df.dateFormat = format
df.date(from: self)
}
}
Note also that this approach will create a new date formatter every time you call this method. You should avoid that as well creating a static formatter. I would also make sure if the date string is using the current timezone. Usually it is UTC timezone.
From UTC to local time doesn't consider daylight saving swift
The issue here is the lack of the date. You are always passing only the time components without the day so the daylight savings time Will always be correspondent to January 1st 2001. If you need today’s date you need to set the date formatter defaultDate property to the startOfDay for today. Btw don’t forget to set the locale first to “en_US_POSIX” before setting the fixed date format.
UIDatePicker does not respect Daylight Savings Time
According to Apple's Documentation you'll want to call this method:
Declaration
func daylightSavingTimeOffset(for date: Date = default) -> TimeInterval
Parameters
date
The date to use for the calculation. The default value is the current
date.
Related Topics
Swift & Firebase - How to Store More User Data Other Than Email and Password
For-In Loop and Type Casting Only for Objects Which Match Type
Core Data Predicate Not Working
My Uiviewcontroller Is Not Filling the Entire Screen
How Do Generators Whose Element Is Optional Know When They'Ve Reached the End
Is There a Preferred Technique to Prohibit Pasting into a Uitextfield
Programatic Constraints Not Obeyed
Adding Swift 3 Packages to Xcode 8 Using the Swift Package Manager
iOS - Add Image and Text in Title of Navigation Bar
How to Deallocate Realitykit Arview()
Why Is the Swift Compiler Marking This as an Error
Physicsbody: Could Not Create Physics Body
Save & Retrieve Tableviewcell Checkmark Using Nsuserdefaults in Swift
Any Way to Chain == and || Operands
Google API - Invalid Credentials