0

I just need a time picker in my, so using date picker and setting it to time mode. I wish to set the time on it programmatically and wrote the code below. However, dateFormatter.date returns nil for a valid string and I can't understand why.

let dateFormatter = DateFormatter()
 dateFormatter.dateFormat = (isDeviceTimeFormat24Hours ? "HH:mm" : "hh:mm aa")
let date = dateFormatter.date(from: "17:00")
timePicker.date = date!
timePicker.datePickerMode = UIDatePicker.Mode.time

Why would my 'date' object be nil in this case?

Edit: If I set my device time format to 24 hours, then this works fine. But if it is 12 hours, then it doesn't. So something is wrong with "hh:mm aa". After googling, I also tried "h:mm a", still didn't work for me.

tech_human
  • 6,592
  • 16
  • 65
  • 107
  • You just need to set your DateFormatter's locale to `"en_US_POSIX"` – Leo Dabus Oct 12 '19 at 15:50
  • use this dateformatter extension ////////////////////////////////////////////////////////////// extension DateFormatter { func changeFormate(isTweleveHours:Bool = true) { if(isTweleveHours){ let twelveHourLocale = Locale(identifier: "en_US_POSIX") self.locale = twelveHourLocale } else{ let twentyFourHourLocale = Locale(identifier: "en_GB") self.locale = twentyFourHourLocale } } } //////////////////////////////////////////// – umer farooqi Oct 12 '19 at 15:55

0 Answers0