Pramod Shukla
Pramod Shukla

Reputation: 235

Date picker with type time

Time picker not allowing me to set max time, i am using below lines of code :

    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

Upvotes: 0

Views: 169

Answers (2)

AtulParmar
AtulParmar

Reputation: 4570

Use the following code to set min and max time, I hope it helps you.

With the help of DateComponents set hour and minutes in Date and then assign min and max value of 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()

Upvotes: 0

Asad Ali Choudhry
Asad Ali Choudhry

Reputation: 5271

Try this

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

Upvotes: -1

Related Questions