Benipro98
Benipro98

Reputation: 313

Swift: Date can't parse "yyyy-MM-dd'T'HH:mm:ss" String

I'm currently trying to call an Api which then returns me some information along with a change date. Afterwards I want to display the Date in the format "dd.MM.yyyy". The Date I get from the Api looks like this: "2020-03-20T19:30:00". Therefore, I used the solution in this question: How to get time from YYYY-MM-dd'T'HH:mm:ss.sssZ to make it look like the format I want.

Unfortunally when I try to parse the date which I get from the Api I always get a nil value.

The code I wrote looks as follows:

let inputFormatter : DateFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFormatter : DateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"

//date is always nil 
let date = inputFormatter.date(from: content?.DateTime ?? "2020-03-20T19:30:00")

dateLabel.text = dateFormatter.string(from: date ?? Date())

Does somebody know why I always get a nil value and if the way I'm converting the dates is a good/bad practice?

Upvotes: 1

Views: 1537

Answers (1)

kerim.ba
kerim.ba

Reputation: 286

@Leo Dabus gave very good points. Interestingly, I have tested your code in playground using the string "2020-03-20T19:30:00" and it works perfectly even without setting locale. I think something is wrong with content?.DateTime. The sample code you should probably use:

`

let dateFormatter : DateFormatter = DateFormatter()
let locale = Locale(identifier: "en_US_POSIX")

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = locale

guard let date = dateFormatter.date(from: "2020-03-20T19:30:00") else {
  fatalError("Could not create date")
}
print(date)

`

Upvotes: 1

Related Questions