I've got a UIDatePicker in Time mode with an interval of 15 minutes.
Let's say it's 7:22PM. The value that the date picker shows per default is the current time rounded to the next higher/lower value, in this case, it's 7:15PM. If the user interacts with the date picker, the value that's shown is also the value returned. However if there hasn't been any user interaction and I get the time with [UIDatePicker date]
the return value is the exact current time, i.e. 7:22 to stick with the example. Is there any way to always get the value that's actually shown on the date picker instead of the current unrounded time, even if the user hasn't explicitly picked a value? I've already tried to set the picker manually with [UIDatePicker setDate:[NSDate date]]
but that doesn't change the behavior.
Any hints? Thanks in advance!
I've modified @ima747 's answer for Swift 3/4 and as an extension of UIDatePicker
. picker.clampedDate
extension UIDatePicker {
/// Returns the date that reflects the displayed date clamped to the `minuteInterval` of the picker.
/// - note: Adapted from [ima747's](http://stackoverflow.com/users/463183/ima747) answer on [Stack Overflow](http://stackoverflow.com/questions/7504060/uidatepicker-with-15m-interval-but-always-exact-time-as-return-value/42263214#42263214})
public var clampedDate: Date {
let referenceTimeInterval = self.date.timeIntervalSinceReferenceDate
let remainingSeconds = referenceTimeInterval.truncatingRemainder(dividingBy: TimeInterval(minuteInterval*60))
let timeRoundedToInterval = referenceTimeInterval - remainingSeconds
return Date(timeIntervalSinceReferenceDate: timeRoundedToInterval)
}
}