Skip to content

Instantly share code, notes, and snippets.

@norsez
Created June 21, 2017 05:18
Show Gist options
  • Save norsez/342bdff967d0ac4bc357d3a1e7edfcb2 to your computer and use it in GitHub Desktop.
Save norsez/342bdff967d0ac4bc357d3a1e7edfcb2 to your computer and use it in GitHub Desktop.
Swift 3: Date <-> ISO 8601 String conversion
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)
}
}
@pimoux
Copy link

pimoux commented Jan 20, 2022

It works for me, congratulations 💪

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment