I'm currently working with dataPicker and in my project specification I need to set time to midnight and then to noon and I'm doing it like this:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yy."
datePicker.date = Calendar.current.startOfDay(for: datePicker.date)
datePicker.date = datePicker.date.addingTimeInterval(12 * 3600)
And it is working for all cases but not for the first day in date picker that user can select and that is the current day. Also in other date picker in which minimum date is 7 days before current I have same issue, date picker does not want to set time to midnight and set it to current time for the first date user can select. After that the last line works so it add 12 hours to current time, so I get next day instead of current which I don't want. Why for the first day in date picker this line doesn't work
datePicker.date = Calendar.current.startOfDay(for: datePicker.date)
and it doesn't want to set time to midnight?
Thank you in addition.
CodePudding user response:
The datePicker.date cannot be set to a date before datePicker.minimumDate. In your case you've set datePicker.miniumDate to 7 days ago. So if the current date and time is 2022/07/25 13:00, the datePicker.miniumDate will be 2022/07/18 13:00 while startOfDay() will be 2022/07/18 00:00 which is before datePicker.minimumDate.