Swift3 如果让ISO8601DateFormatter从字符串

Swift3 如果让ISO8601DateFormatter从字符串,swift3,swift4,Swift3,Swift4,我有一个返回对象日期的响应,有时返回年份,有时返回带有ISO8601DateFormatter样式1995-01-01T00:00:00Z的日期 问题是如何获得一个if-let,它可以识别值是字符串中的年份还是字符串中的ISO8601日期。我最后这样做了: let pulledDate = "1995-01-01T00:00:00Z" let dateFormatter = ISO8601DateFormatter() dateFormatter.format

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

问题是如何获得一个if-let,它可以识别值是字符串中的年份还是字符串中的ISO8601日期。

我最后这样做了:

      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")
      }
使用DateFormatter和ISO格式甚至ISO8601DateFormatter转换日期字符串。如果失败了,那就是字符串