Swift 4 Date Picker使用分钟间隔错误的值 [英] Swift 4 Date Picker wrong value using minuteinterval

查看:77
本文介绍了Swift 4 Date Picker使用分钟间隔错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期选择器,分钟间隔设置为15分钟。
当我的屏幕出现时,我看到(例如)今天18:45,但是如果打印此值,则得到: 18:43。
如果我从选择器中选择日期,它将正常工作。

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


推荐答案

问题是,如果不手动设置DatePicker的初始值,则将其设置为当前时间。您可以获取当前分钟,将其转换为Double,将其除以目标分钟间隔,向上舍入,再乘以目标间隔,然后将结果提醒除以60。现在,您可以将结果转换回整数并使用Calendar的下面的方法来查找与您的分钟组件匹配的下一个日期:

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"

这篇关于Swift 4 Date Picker使用分钟间隔错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆