Swift 4 字符串中的日期格式始终为零

Swift 4 DateFormater from string always nil

我有一个这样的约会对象:

2020-10-01T00:00:00

我正在尝试使用以下格式对其进行格式化:

let formatter = DateFormatter()

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

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

但它总是 return 零。

这是我的完整代码,我做错了什么?

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

就您所显示的而言,您的代码没有任何内容。例如,这很好用:

let s = "2020-10-01T00:00:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateRequired = formatter.date(from: s)

由于它有效,我们可以得出结论,self.objects[indexPath.row]["DateRequired"] 可能不是您认为的那样。另一种可能是您需要设置语言环境:

let s = "2020-10-01T00:00:00"
let formatter = DateFormatter()
formatter.locale = Locale(identifier:"en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateRequired = formatter.date(from: s)

但是请注意,您不应在此处使用 DateFormatter;这个用例正是 ISO8601DateFormatter 的用途,你会更喜欢使用它而不是试图重新发明这个轮子。