I am having the user pick a date and time and saving that as a string I display in a text field, like so:
@objc func dealDateSelected(sender: UIDatePicker) {
let date = DateFormatter()
date.dateStyle = .short
date.timeStyle = .short
date.timeZone = TimeZone.current
date.locale = Locale.current
limitedTimeTextField.text = date.string(from: sender.date)
}
Then I am attempting to convert that text field back to a date object later, but I cannot get it to work. The format looks like this: "6/7/20, 10:10 PM". All of the things I've seen to convert date are in a different format than what I'm using. I saw something about kCFDateFormatterShortStyle but I cannot find where to access it.
When I try this
//Check Time
var dateEnding: Date?
if(limitedTimeSwitch.isOn) {
if let dateChosen = limitedTimeTextField.text {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.locale = Locale.current
formatter.dateStyle = .short
formatter.timeStyle = .short
dateEnding = formatter.date(from: dateChosen)
}
}
I only get nil back. I've also tried using
dateEnding = ISO8601DateFormatter().date(from: dateChosen)
but that also returns nil. My string is coming through properly as "6/7/20, 10:10 PM", in that format.
What format do I need to use to get it converted back into a date? I thought it would be simple since all I'm doing is converting date to string, then back again, but it's causing so much trouble.