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)
}
}
@norsez
Copy link
Author

norsez commented Jun 21, 2017

Not really sure about the Locale to use whether it's sufficiently generalized. Any suggestions?

@simbaste
Copy link

Thanks it work :)

@ElCasador
Copy link

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
}

@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