UIDatePicker with 15m interval but always exact time as return value UIDatePicker with 15m interval but always exact time as return value ios ios

UIDatePicker with 15m interval but always exact time as return value


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)    }}


This isn't a perfect solution but it works for me. I've taken it from another post and modified it to accept different values.

- (NSDate*)clampDate:(NSDate *)dt toMinutes:(int)minutes {    int referenceTimeInterval = (int)[dt timeIntervalSinceReferenceDate];    int remainingSeconds = referenceTimeInterval % (minutes*60);    int timeRoundedTo5Minutes = referenceTimeInterval - remainingSeconds;     if(remainingSeconds>((minutes*60)/2)) {/// round up        timeRoundedTo5Minutes = referenceTimeInterval +((minutes*60)-remainingSeconds);                }    return [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)timeRoundedTo5Minutes];}

Feed it an input date and a minute value (taken from the UIDatePicker.minuteInterval in the case of this thread) and it will return a time clamped to that interval which you can feed to the picker.


@ima747 is right if I've changed date picker's default value then it's working fine and if I've read date from picker control without onChange then it's returning wrong date value.
But I've checked that, date picker control have set default date (current date and may be it use nearest time milliseconds) If I set it to custom date and also set time to any date and 1:00:AM so now my time picker always open with 1:00:AM instead of current timeenter image description here