3

I have a datepicker with "minuteinterval" setted to 15 minutes. When my screen appear I see (for example) "today 18:45" but If I print this value I get: "18:43". While if I select date from picker it works correctly.

    override viewDidLoad(){
       super.viewDidLoad
       pickerTime.minuteInterval = 15  
       print(pickerTime.date.description)
      }  
TillMoss
  • 37
  • 6
  • Does this answer your question? [UIDatePicker is set to 15 minute intervals, but the date if the user doesn't scroll isn't in 15 minute intervals](https://stackoverflow.com/questions/42662081/uidatepicker-is-set-to-15-minute-intervals-but-the-date-if-the-user-doesnt-scr) – timbre timbre Feb 05 '20 at 17:40

1 Answers1

0

The problem there is that DatePicker initial value is set to the current time if you don't set its value manually. You can get the current minute, convert it to Double, divide it by the target minute interval, round it up, multiply by the target interval and truncate the result reminder dividing by 60. Now you can convert the result back to integer and use Calendar's method below to find the next date matching your minute component:

func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy = .first, direction: Calendar.SearchDirection = .forward) -> Date?

extension Date {
    var minute: Int { Calendar.current.component(.minute, from: self) }
    func nextDate(roundedTo minutes: Int) -> Date {
        Calendar.current.nextDate(after: self,
                                  matching: .init(minute: Int((Double(minute)/Double(minutes)).rounded(.up) * Double(minutes)) % 60),
                                  matchingPolicy: .nextTime)!
    }
}

to set the current date to the nearest interval:

let datePicker = UIDatePicker()
let now = Date()  // "Feb 5, 2020 at 6:48 PM"
datePicker.date = now.nextDate(roundedTo: 15)
datePicker.minuteInterval = 15
datePicker.date   // "Feb 5, 2020 at 7:00 PM"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571