如果让来自String的ISO8601DateFormatter

时间:2018-01-18 09:38:10

标签: swift3 swift4

我有一个返回对象日期的响应,有时会返回年份,有时会返回ISO8601DateFormatter样式的日期(1995-01-01T00:00:00Z)

问题是我如何得到一个if let,它可以识别值是一年的字符串或字符串的ISO8601Date。

1 个答案:

答案 0 :(得分:1)

我最终这样做了:

      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")
      }