Sham Dhiman
Sham Dhiman

Reputation: 1566

Hide past date and time from date picker swift

i'm trying to hide date picker past date. but i m not able to hide. is there any way to hide past date and time. I was able to disable the past date when i have set to minimum date. So is there any way to hide the past date from date picker.

Screen Shot

Upvotes: 3

Views: 6796

Answers (2)

Sham Dhiman
Sham Dhiman

Reputation: 1566

var dateCollection = [Date]()

func selectedDate()->Int{
    dateCollection = buildDateCollection()
    var row = 0
    for index in dateCollection.indices{
    let today = Date()
    if Calendar.current.compare(today, to: dateCollection[index], toGranularity: .day) == .orderedSame{
row = index
        }
    }
    return row
}

func buildDateCollection()-> [Date]{
   dateCollection.append(contentsOf: Date.nextYear())
   return dateCollection
}

func formatDatePicker(date: Date) -> String{
    formatter.dateFormat = DATE_PICKER_FORMAT_CUSTOM
    return formatter.string(from: date)
}

func formatDate(date: Date) -> String{
    formatter.dateFormat = SECURIY_CONC_CLIENT_FORMAT_PNDING
    return formatter.string(from: date)
}

override func viewDidLoad() {
    super.viewDidLoad()        
    let _ = selectedDate()
}

func setPickerView() {
    picker.tag = tag
    picker.delegate = self
    txtField_Date.dataSource = self
    txtField_Date.inputView = picker
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
     return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return dateCollection.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return formatDatePicker(date: dateCollection[row])
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
     txtField_Date.text = formatDate(date: self.dateCollection[row])
}

Output Screen Shot:

Screen Shot

Upvotes: 0

Rahul Umap
Rahul Umap

Reputation: 2869

Solution :

Set minimum date of date picker as a Current Date.

datePicker.minimumDate = Date()

For a reference you can follow this SO questions:

How to hide future or past dates in UIDatePickerView

iOS: UIDatePicker "remove" dates outside min and max dates

Note: Minimum date property will disable the selection of past dates but it won't hide the dates rather it will grayed out it.

Upvotes: 8

Related Questions