1

How to use ISO8601DateFormatter to convert a String to Date?

let iSO8601DateFormatter = ISO8601DateFormatter()
let string = iSO8601DateFormatter.string(from: Date()) //2019-12-04T08:23:27Z
let date = iSO8601DateFormatter.date(from: string)  //nil ?

The code above run in iPhone8 simulator with Xcode 11.2.1, I get nil.

But it works in the Playground of same Xcode.

Can any one help me to point what's wrong about my doing?

Anton Tropashko
  • 5,486
  • 5
  • 41
  • 66
Jungen yan
  • 222
  • 2
  • 11

2 Answers2

2

It seems a bug in Xcode11 and swift 5. The date actually is not nil, but in debug, it is showed as nil.

let date = Date()
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime]
let dateString = formatter.string(from: date)
if let myDate = formatter.date(from: dateString){
      print(myDate) //2019-12-08 02:22:26 +0000
}

You can see more about the bug at this SO post

Jungen yan
  • 222
  • 2
  • 11
0

You can specify iSO8601 date formate to the NSDateFormatter to get Date:

  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
  let date = dateFormatter.date(from: dateString)
  print(date) //2019-12-04 12:46:00 +0000

You can check types of date formats at here.

I hope this may be helpful to you.

Community
  • 1
  • 1
Abhishek Patel
  • 121
  • 1
  • 1
  • 11
  • 1
    Thanks for your help. I also test the DateFormatter: ```let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let string = dateFormatter.string(from: Date()) let date = dateFormatter.date(from: string)``` and the date still is nil in the simulator, but works in the Playground. – Jungen yan Dec 04 '19 at 13:21
  • @Jungenyan I check your code. It is working in my simulator. Check with an iOS device. There is no problem in your code. – Abhishek Patel Dec 05 '19 at 04:36
  • 1
    I've checked my code again in the simulator and my iPhone7, the date still is nil. – Jungen yan Dec 06 '19 at 01:38