Created
June 21, 2017 05:18
-
-
Save norsez/342bdff967d0ac4bc357d3a1e7edfcb2 to your computer and use it in GitHub Desktop.
Swift 3: Date <-> ISO 8601 String conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Date { | |
static func ISOStringFromDate(date: Date) -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.locale = Locale(identifier: "en_US_POSIX") | |
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") | |
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" | |
return dateFormatter.string(from: date).appending("Z") | |
} | |
static func dateFromISOString(string: String) -> Date? { | |
let dateFormatter = DateFormatter() | |
dateFormatter.locale = Locale(identifier: "en_US_POSIX") | |
dateFormatter.timeZone = TimeZone.autoupdatingCurrent | |
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" | |
return dateFormatter.date(from: string) | |
} | |
} |
Thanks it work :)
removed line #5
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
created this function below with your's to get the local time in Date() format
func setLocalTime(date: Date) -> Date {
let date = Date.dateFromISOString(string: Date.ISOStringFromDate(date: date))!
return date
}
It works for me, congratulations 💪
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not really sure about the Locale to use whether it's sufficiently generalized. Any suggestions?