6

Suppose today's date is 16 May 2016, I want to restrict the user to display date up-to 16 jun 2016.

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
Nisha Nair
  • 327
  • 1
  • 5
  • 17

5 Answers5

13

Edit

Swift 3

    let datePicker = UIDatePicker()
    datePicker.maximumDate = Date()

swift 2

    let datePicker = UIDatePicker()
    datePicker.maximumDate = NSDate()

Restrict user to particular time interval

Try This: It will restrict user to select date greater than one month from current date.

let datePicker = UIDatePicker()
let secondsInMonth: NSTimeInterval = 30 * 24 * 60 * 60
datePicker.maximumDate = NSDate(timeInterval: secondsInMonth, sinceDate: NSDate())
Community
  • 1
  • 1
AkBombe
  • 638
  • 4
  • 10
4

In swift 2.0, use the property maximumDate to solve your problem.

You can use the code like this..

let datePicker = UIDatePicker()
datePicker.maximumDate = NSDate()
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Himanshu
  • 2,832
  • 4
  • 23
  • 51
2

set the maximumDate property of UIDatePicker.

DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
Surjeet Rajput
  • 1,251
  • 17
  • 24
2

The logic is like this suppose today is 16th May 2016 and you want to add 30 days then below logic would be helpful to you

 // Initialize stringified date presentation
var myStringDate: String = "2016-05-16"
    // How much day to add
var addDaysCount: Int = 30
    // Creating and configuring date formatter instance
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
    // Retrieve NSDate instance from stringified date presentation
var dateFromString: NSDate = dateFormatter.dateFromString(myStringDate)
    // Create and initialize date component instance
var dateComponents: NSDateComponents = NSDateComponents()
dateComponents.day = addDaysCount
    // Retrieve date with increased days count
var newDate: NSDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: dateFromString, options: 0)
NSLog("Original date: %@", dateFormatter.stringFromDate(dateFromString))
NSLog("New date: %@", dateFormatter.stringFromDate(newDate))
// Clean up
dateComponents, dateComponents = nil
dateFormatter, dateFormatter = nil

New date what you get can be set to the UIDatePicker.

iAnkit
  • 1,940
  • 19
  • 25
2

You can set both Max date and Min date programmatically.

Use following code for iOS 8+

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:1];
NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

/* Optional for your case */
[comps setYear:-30];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMaximumDate:maxDate];
[datePicker setMinimumDate:minDate]
NSPratik
  • 4,714
  • 7
  • 51
  • 81