I am trying to set the default time of the DatePicker(Which only asks for Hour and Minute) to 7:00 using codes below:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date1 = dateFormatter.date(from: "07:00")
datePicker1.date = date1!
and it works just fine on all of my devices and simulators, but I’ve got one crash report from my users that when unwrapping date1
, it unexpectedly found nil. I can’t reproduce the same error and my app works so fine when I’m testing. I don’t know how to do fix the problem, neither reproducing it. What should I do?
Besides, when running the code in swift playground, I found a strange phenomenon. Why is it happening? Why did the value of date1
change when I print it?
2
Answers
I think the problem doesn't lie on DatePicker, but on String-Date conversion. Thanks to Kush Bhavsar, I've figured out a solution which sets locale of the DateFormatter to "en_gb". So you can write code like this:
so it works fine on both 12Hrs and 24Hrs phone.
Alternatively, you can write an extension like this if you prefer 24Hrs mode as default when writing codes(like me):
Usage:
You can easily opt to choose the
datePicker
in 12hr format by setting itslocal
property.For 24-Hour Format:
For 12-Hour Format:
Extension to set the Date/time:
Usage:
To check whether current device’s formate is 12/24 Hour :