UIDatePicker is set to 15 minute intervals, but the date if the user doesn't scroll isn't in 15 minute intervals

最后都变了- 提交于 2020-07-07 06:52:52

问题


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?


回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/42662081/uidatepicker-is-set-to-15-minute-intervals-but-the-date-if-the-user-doesnt-scr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!