当项目为 Swift 4 • iOS 11 或更高的版本用一下写法
extension Formatter {
static let iso8601: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
}
使用方法
let dateString = Formatter.iso8601.string(from: Date()) // "2018-01-23T03:06:46.232Z"
if let date = Formatter.iso8601.date(from: dateString) {
print(date) // "2018-01-23 03:06:46 +0000\n"
}
当项目为 Swift 3.0.2 或 iOS 11 以下的版本,用下面的写法
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
extension Date {
var iso8601: String {
return Formatter.iso8601.string(from: self)
}
}
extension String {
var dateFromISO8601: Date? {
return Formatter.iso8601.date(from: self) // "Mar 22, 2017, 10:22 AM"
}
}
使用方法
let stringFromDate = Date().iso8601 // "2017-03-22T13:22:13.933Z"
if let dateFromString = stringFromDate.dateFromISO8601 {
print(dateFromString.iso8601) // "2017-03-22T13:22:13.933Z"
}