I have a textfield and when it is selected a datepicker pops up instead of a keyboard, but it only updates with todays date the first time. The user changes the date, but th
datePicker = UIDatePicker(frame:CGRect(x: 0, y: self.view.frame.size.height-180 , width: self.view.frame.size.width, height: 200))
self.view.addSubview(datePicker)
datePicker.datePickerMode = UIDatePickerMode.dateAndTime
datePicker.isHidden = true
button.isSelected = false
datePicker.addTarget(self, action: #selector(self.dateSelected), for: UIControlEvents.valueChanged)
@objc func dateSelected()
{
let dateformatter1 = DateFormatter()
dateformatter1.dateFormat = "ccc, d MMM yyy"
let dateString1 = dateformatter1.string(from: datePicker.date)
print("Date Selected \(dateString1)")
labelDate.text = dateString1
let dateformatter2 = DateFormatter()
dateformatter2.dateFormat = "dd-MM-yyyy"
let dateString2 = dateformatter2.string(from: datePicker.date)
print("Date Selected \(dateString2)")
let dateformatter3 = DateFormatter()
dateformatter3.dateFormat = "dd/MM/yyyy"
let dateString3 = dateformatter3.string(from: datePicker.date)
print("Date Selected \(dateString3)")
let dateformatter4 = DateFormatter()
dateformatter4.dateFormat = "dd MMMM yyyy hh:mm a"
let dateString4 = dateformatter4.string(from: datePicker.date)
print("Date Selected \(dateString4)")
}
This article on DatePicker and NSDateFormat helped me a lot.