3

I am creating an iOS application that uses two UIDatePickers. They show just hours and minutes (my app still uses the month, day, and year though). In main.storyboard I have set the UIDatePickers' Date values to Current Date. And, I have set their interval to 15 minutes.

The issue is that if I don't scroll the UIDatePickers, the date value I get from them isn't in 15 minute intervals. If I scroll them I do get 15 minute intervals.

Example: The actual time is 8:47PM. The UIDatePicker loads to 8:45PM. The date value I get from it without scrolling will be 8:47PM, not 8:45PM. If I scroll up to 8:30PM or 9:00PM, I will get those times.

I would like to get my time in 15 minute intervals. Is there a way to do this, or do I have to write a function to round to the nearest 15 minute interval?

Nishant
  • 131
  • 2
  • 12
  • Possible duplicate of [UIDatePicker with 15m interval but always exact time as return value](https://stackoverflow.com/questions/7504060/uidatepicker-with-15m-interval-but-always-exact-time-as-return-value) – pkamb Sep 17 '21 at 04:30

3 Answers3

5

Actually, it turns out someone has written an extension for this in Swift 3. My mistake. This solution worked perfectly for me.

https://stackoverflow.com/a/42263214/7025448

Community
  • 1
  • 1
Nishant
  • 131
  • 2
  • 12
1

I came across this issue and succeeded in implementing a method to resolve this:

- (NSDate *)roundToNearestQuarterHour:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal | NSCalendarUnitWeekOfYear;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    NSInteger roundedToQuarterHour = round((components.minute/15.0)) * 15;
    components.minute = roundedToQuarterHour;
    return [calendar dateFromComponents:components];
}

So you call like this:

NSDate *now = [self roundToNearestQuarterHour:[NSDate date]];

Unfortunately I come from an Objective C background and inexperienced with Swift.

The Mach System
  • 6,703
  • 3
  • 16
  • 20
0

You have to set the datePicker's date ideally in a function you call in viewDidLoad.

// Do your date computation here to get nearestFifteenMinuteInterval
self.yourDatePicker.date = nearestFifteenMinuteInterval

For the computation use the Date's timeInterval methods/ computed properties which use the number of seconds.

For example, the timeIntervalSince1970 is the number of seconds that elapsed since January 1, 1970 0:00:00.

Also you can use the start of the day as a reference date using this:

let START_OF_DAY: Date = {
    let calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
    return calendar.startOfDay(for: Date())
}()
hooliooo
  • 528
  • 1
  • 5
  • 13