类型为时间的日期选择器

时间:2019-05-23 11:10:14

标签: swift dateformatter nsdatepicker

时间选择器不允许我设置最大时间,我正在使用以下代码行:

    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mm a"
    let locale = NSLocale(localeIdentifier: "en_US_POSIX")
    formatter.locale = locale as Locale

    timePicker.datePickerMode = .time


    let min = formatter.date(from: "08:00 AM") //createing mintime
    let max = formatter.date(from: "11:00 PM") //creating max time

    print(max)

    timePicker.minimumDate = min  //setting min time to picker
    timePicker.maximumDate = max  //setting max time to picker

    timePicker.minuteInterval = 30

2 个答案:

答案 0 :(得分:0)

尝试一下

 let max = Calendar.current.date(bySettingHour: 11, minute: 0, second: 0, of: Date())!
 timePicker.maximumDate = max

答案 1 :(得分:0)

使用以下代码设置最小和最大时间,希望对您有所帮助。

借助DateComponentsDate中设置小时和分钟,然后分配datePicker的最小值和最大值

let startHour: Int = 6
let endHour: Int = 23
let date1: NSDate = NSDate()
let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
var components: DateComponents = gregorian.components(([.day, .month, .year]), from: date1 as Date)
components.hour = startHour
components.minute = 0
components.second = 0
let startDate: Date = gregorian.date(from: components)!
components.hour = endHour
components.minute = 0
components.second = 0
let endDate: Date = gregorian.date(from: components)!
timePicker.datePickerMode = .Time
timePicker.minimumDate = startDate
timePicker.maximumDate = endDate
timePicker.setDate(startDate, animated: true)
timePicker.reloadInputViews()