Swift 4 DateFormater from string always nil

I have a date like so:

2020-10-01T00:00:00

And I'm trying to format it using this:

let formatter = DateFormatter()

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

let dateRequired = formatter.date(from: self.objects[indexPath.row]["DateRequired"] as! String)

But it always return nil.

Here is my full code, what am I doing wrong?

let formatter = DateFormatter()

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

let dateRequired = formatter.date(from: self.objects[indexPath.row]["DateRequired"] as! String)
                
formatter.dateFormat = "yyyy-MM-dd"
                
let dateRequiredString = formatter.string(from: dateRequired!)

self.dateRequiredTextField.text = dateRequiredString
                
self.dateRequiredTextField.placeholder = "Date Required"
                
self.datePicker.datePickerMode = .date
                
let toolbar = UIToolbar()
                
toolbar.sizeToFit()
                
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneButtonPressed))
                
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
                
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelButtonPressed))
                
toolbar.setItems([cancelButton, space, doneButton], animated: false)
                
self.dateRequiredTextField.inputAccessoryView = toolbar
                
self.dateRequiredTextField.inputView = self.datePicker


Read more here: https://stackoverflow.com/questions/64394170/swift-4-dateformater-from-string-always-nil

Content Attribution

This content was originally published by user979331 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: