如果让 ISO8601DateFormatter 来自 String
if let ISO8601DateFormatter from String
我的回复是 returns 对象的日期,有时 returns 年份,有时 returns ISO8601DateFormatter 样式的日期 (1995-01-01T00: 00:00Z)
问题是我怎样才能得到一个 if let 来识别何时值是字符串形式的年份或字符串中的 ISO8601Date。
我最终这样做了:
let pulledDate = "1995-01-01T00:00:00Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
if let date = dateFormatter.date(from: pulledDate ?? ""){
let units: Set<Calendar.Component> = [.year]
let comps = Calendar.current.dateComponents(units, from: date)
print("It is a date year = \(comps.year)")
}
else{
print("It is not a date")
}
我的回复是 returns 对象的日期,有时 returns 年份,有时 returns ISO8601DateFormatter 样式的日期 (1995-01-01T00: 00:00Z)
问题是我怎样才能得到一个 if let 来识别何时值是字符串形式的年份或字符串中的 ISO8601Date。
我最终这样做了:
let pulledDate = "1995-01-01T00:00:00Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
if let date = dateFormatter.date(from: pulledDate ?? ""){
let units: Set<Calendar.Component> = [.year]
let comps = Calendar.current.dateComponents(units, from: date)
print("It is a date year = \(comps.year)")
}
else{
print("It is not a date")
}