0

I stuck to convert string to date, my date string is "2021-03-25T06:35:36.372245" Unable to convert it into date formate. I used the code but unable to convert, i got nil. My code is

   let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss.ZZZZZZ" ( also tried SSSSSS)
    let dte = dateFormatter.date(from: dateTime)

but unable to parse it. Kindly help me out.

  • Try this formate "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" – Raja Kishan Mar 29 '21 at 11:15
  • Doesn't seem to be TimeZone to me, so not the "Z", but more seconds, to the "S". Try `"yyyy-MM-dd'T'HH:mm:ss.SSSSSS"` If you print `dateFormatter.string(from: Date())`, you'll see that the `T` is breaking, you need to escape it. – Larme Mar 29 '21 at 11:16
  • thanks @Larme its working i used the same but not used T with ''('T'), T is the separator so their is need to write T with '' . – user3120670 Mar 29 '21 at 11:20
  • https://stackoverflow.com/questions/28016578/how-can-i-parse-create-a-date-time-stamp-formatted-with-fractional-seconds-utc – eildiz Mar 29 '21 at 11:29

2 Answers2

1

You forget '' arround T

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Do this

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let dte = dateFormatter.date(from: dateTime)
ami solani
  • 351
  • 1
  • 5
  • This is wrong. You should never escape the `Z`. Btw there is no timezone in the date string so you should remove it and set the dateFormatter's timezone to zero seconds from GMT – Leo Dabus Mar 29 '21 at 12:37
  • Sorry it was my mistake, thanks for pointing – ami solani Mar 29 '21 at 12:52