Dateformatter日期字符串返回nil

时间:2019-07-12 07:49:12

标签: ios swift date

当我使用DatePicker设置日期

它说没有了

尽管我检查了日期字符串格式是否正确

并且dateFormat设置为我想要的格式。

这里是代码

class DatePickerViewController: UIViewController {

var originDate: String!{ 
        didSet{
            //print("\(originDate)") is like "2019/07/12"
            selectedDate = dateFormatter.date(from: originDate)
           //print("\(selectedDate)") is nil
            datePicker.setDate(selectedDate, animated: true)
        }
 }

var selectedDate: Date!
var dateString: String = "yyyy/MM/dd"
var dateFormatter: DateFormatter = DateFormatter()

override func viewDidLoad() {

        dateFormatter.dateFormat = dateString

}

ShowPickerViewController调用DatePickerViewController

class ShowPickerViewController:UIViewcontroller {

   @IBAction func showDatePicker(_ sender: Any) {

   let vc = DatePickerViewController()

   vc.originDate = sender.text // "2019/07/12"

   present(vc, animated: true)

   }

}

1 个答案:

答案 0 :(得分:0)

以结束符初始化日期格式化程序

let dateFormatter: DateFormatter = {
   let formatter = DateFormatter()
   formatter.dateFormat = "yyyy/MM/dd"
   return formatter
}()

并删除viewDidLoad

中的行