Tejveer Sambariya
Tejveer Sambariya

Reputation: 271

how to restrict in datepicker current date to next 15days in swift 2.0

I am trying this code but it is not working. thanks to all. I am using uidatepicker with select minimumDate. but require current date with additional 15 days in datepicker swift 2.0.

override func viewDidLoad() {
 let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.Date
        sender.inputView = datePickerView
        datePickerView.minimumDate = datePickerView.date

        //datePickerView.maximumDate = datePickerView.date

 datePickerView.addTarget(self, action: #selector(BookAppointmentView.datePickerValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
        }

func datePickerValueChanged(sender:UIDatePicker)->NSDate {

        let baseDate:NSDate = NSDate()

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"


        DatePickerField.text = dateFormatter.stringFromDate(sender.date)
        print("date of bookAppointment\(DatePickerField.text!)")

       return newDate!

    }

Upvotes: 0

Views: 136

Answers (2)

Stefan van der Lee
Stefan van der Lee

Reputation: 83

There are multiple ways to accomplish this. dateByAddingTimeInterval is one, in which you add time in seconds:

datepickerView.minimumDate = NSDate() // current date
datepickerView.maximumDate = NSDate().dateByAddingTimeInterval(1296000) // date + 15 days

You can also do:

datepickerView.minimumDate = NSDate() // current date
let maxDateComponent = NSDateComponents()
maxDateComponent.day = //days you want to add
datePickerView.maximumDate = NSCalendar.currentCalendar().dateByAddingComponents(maxDateComponent, toDate: NSDate(), options: NSCalendarOptions.init(rawValue: 0))

In which you add the time in days.

Upvotes: 1

Prabhu.Somasundaram
Prabhu.Somasundaram

Reputation: 1390

I hope this extension method helps

extension NSDate {
    func dateByAddingDays(days:Int) -> NSDate? {
        let c:NSDateComponents = NSDateComponents()
        c.day = days;
        return NSCalendar.currentCalendar().dateByAddingComponents(c, toDate: self, options: [])
    }
}

this code is not tested. but i have used dateByAddingComponents in some cases

Upvotes: 0

Related Questions