61

I want to get the minimum and maximum date from a date picker, but minimum date should be "- 18" of the current date and the maximum date should be "- 100" of current date.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

What I have done so far is :

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

   // NSDate * MinDate = [components year] - 18;

   // NSDate * MaxDate =  [components year] - 100;

   // self.datePicker.minimumDate = MinDate;

   // self.datePicker.maximumDate = MaxDate;

but I cant get this integer to my date format..

tilo
  • 14,009
  • 6
  • 68
  • 85
NSException
  • 1,268
  • 3
  • 14
  • 28

12 Answers12

87

Try this:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:-18];
NSDate *minDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps setYear:-150];
NSDate *maxDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps release];

self.datePicker.minimumDate = minDate;
self.datePicker.maximumDate = maxDate;

It may be easily translated to Swift 4.2:

    let calendar = Calendar(identifier: .gregorian)

    let currentDate = Date()
    var components = DateComponents()
    components.calendar = calendar

    components.year = -18
    components.month = 12
    let maxDate = calendar.date(byAdding: components, to: currentDate)!

    components.year = -150
    let minDate = calendar.date(byAdding: components, to: currentDate)!

    picker.minimumDate = minDate
    picker.maximumDate = maxDate
lucaslt89
  • 2,431
  • 1
  • 20
  • 30
tilo
  • 14,009
  • 6
  • 68
  • 85
  • 1
    Hey @tilto your code is great but it shows disable date also, is it possible to hide them? – Smit Saraiya Mar 11 '16 at 10:38
  • 1
    What do you mean by "disabled date"? – tilo Mar 11 '16 at 10:44
  • 1
    @tilo...how can update the minimum and maximum date range in the date picker view. For example: Configuring the `UIDatePicker` in such a way that it shows month range only from September to March. – Ron Nov 18 '16 at 15:12
  • @tilo "disabled date" mean to not show them in date picker – ArgaPK Jun 02 '18 at 09:43
  • @tilo by saying the "disabled date", I think what SmitSaraiya is trying to tell is that suppose we are in the month of Feb and it's not a leap year so is there any way we can hide the number 29 from the date list and also is it possible to restrict the picker from going to any future years instead of jumping back to currently set maxYear. – Shiv Prakash Jan 10 '20 at 10:55
  • @tilo let suppose I want to set ``` components.year = 0 components.month = -6 let maxDate = calendar.date(byAdding: components, to: currentDate)! ``` Is it right? – Muhammad Hasan Irshad Apr 30 '20 at 04:28
52

Look at this for Swift version. User negative value (-) to subtract and positive value to add date component.

1. Set minimum date

 yourDatePicker.minimumDate = Calendar.current.date(byAdding: .year, value: -1, to: Date())

2. Set maximum date

 yourDatePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 1, to: Date())
Jaywant Khedkar
  • 5,941
  • 2
  • 44
  • 55
Rahul Panzade
  • 1,302
  • 15
  • 12
  • I want to start with today date and my end date will in 2005. then how I'll code it? – Rana Ali Waseem Feb 23 '20 at 12:30
  • **Your start date is ** let startDate = Date() **and End date is ** let currentYear = Calendar.current.component(.year, from: Date()) let endDate = Calendar.current.date(byAdding: .year, value:(2005 - currentYear), to: Date()) – Rahul Panzade Feb 26 '20 at 11:40
  • https://github.com/miraan/CalendarDateRangePickerViewController I'm using this library. I'm not to achieve this with given solution. – Rana Ali Waseem Mar 09 '20 at 17:34
  • This should be the selected answer. Perfect. Precise and does the job! – Junaid Mukhtar Oct 03 '21 at 21:54
22

Swift 5.1

extension UIDatePicker {
    func set18YearValidation() {
        let currentDate: Date = Date()
        var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        var components: DateComponents = DateComponents()
        components.calendar = calendar
        components.year = -18
        let maxDate: Date = calendar.date(byAdding: components, to: currentDate)!
        components.year = -150
        let minDate: Date = calendar.date(byAdding: components, to: currentDate)!
        self.minimumDate = minDate
        self.maximumDate = maxDate
    } }
swift2geek
  • 1,697
  • 1
  • 20
  • 27
16

This is how it would look like in 2017 (Swift 3)

    var components = DateComponents()
    components.year = -100
    let minDate = Calendar.current.date(byAdding: components, to: Date())

    components.year = -18
    let maxDate = Calendar.current.date(byAdding: components, to: Date())

    datePicker.minimumDate = minDate
    datePicker.maximumDate = maxDate
cldrr
  • 1,238
  • 14
  • 22
15

In Swift 2.1:

    let currentDate: NSDate = NSDate()

    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    // let calendar: NSCalendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "UTC")!

    let components: NSDateComponents = NSDateComponents()
    components.calendar = calendar

    components.year = -18
    let minDate: NSDate = calendar.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

    components.year = -150
    let maxDate: NSDate = calendar.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

    self.dateOfBirthUIDatePicker.minimumDate = minDate
    self.dateOfBirthUIDatePicker.maximumDate = maxDate

    print("minDate: \(minDate)")
    print("maxDate: \(maxDate)")
Juan Boero
  • 6,281
  • 1
  • 44
  • 62
King-Wizard
  • 15,628
  • 6
  • 82
  • 76
8

Swift 3.0

 let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
    let currentDate: Date = Date()
    let components: NSDateComponents = NSDateComponents()

    components.year = -150
    let minDate: Date = gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))!

    components.year = -16
    let maxDate: Date = gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))!

    self.datepicker.minimumDate = minDate
    self.datepicker.maximumDate = maxDate
  • Woa, why do `let components: NSDateComponents = NSDateComponents()` just to do `components as DateComponents` later is silly, just start with `let components = DateComponents()` And you are good. Also you will need to declare components as a var not a let. – HuXu7 Dec 21 '17 at 15:39
3

**Minimum and maximum date in UIDatePicker: #Swift

**if you want to select the min and max date between two date value use below simple code: **

for Example : Min Date : 01-04-2017 and Max Date : 31-03-2018

let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
minDateComponent.day = 01
minDateComponent.month = 04
minDateComponent.year = 2017

let minDate = calendar.date(from: minDateComponent)
print(" min date : \(String(describing: minDate))")

var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
maxDateComponent.day = 0
maxDateComponent.month = 03 + 1
maxDateComponent.year = 2018

let maxDate = calendar.date(from: maxDateComponent)
print("max date : \(String(describing: maxDate))")

picker.minimumDate = minDate! as Date
picker.maximumDate =  maxDate! as Date
Kiran Jadhav
  • 3,209
  • 26
  • 29
2

In Objective C, NSDateComponents *comps = [[NSDateComponents alloc] init];

NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];

NSInteger year = components.year;
NSInteger month = components.month;
NSInteger day = components.day;
NSInteger minimumYear = year - 1900;//Given some year here for example
NSInteger minimumMonth = month - 1;
NSInteger minimumDay = day - 1;
[comps setYear:-minimumYear];
[comps setMonth:-minimumMonth];
[comps setDay:-minimumDay];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMinimumDate:minDate];
[datePicker setMaximumDate:[NSDate date]];

The minimum date would be January 01 1900. I hope it works for you all.. :)

In Swift 2.0 or later

    let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian);

    let todayDate = NSDate()

    let components = calendar?.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: todayDate)
    let minimumYear = (components?.year)! - 1900
    let minimumMonth = (components?.month)! - 1
    let minimumDay = (components?.day)! - 1

    let comps = NSDateComponents();
    comps.year = -minimumYear
    comps.month = -minimumMonth
    comps.day = -minimumDay

    let minDate = calendar?.dateByAddingComponents(comps, toDate: todayDate, options: NSCalendarOptions.init(rawValue: 0))

    datePicker.minimumDate = minDate
    datePicker.maximumDate = datePicker.date
Muhammad Noman
  • 1,566
  • 1
  • 15
  • 21
Vinay Podili
  • 335
  • 1
  • 3
  • 16
2

Another case :

Suppose I want to show Date of birth as a Date picker, Dob is within the range of 1/1/1980 to  1/1/2000.

@IBOutlet var datePicker: UIDatePicker!

override func viewDidLoad() {
        super.viewDidLoad()        
        datePicker.datePickerMode = UIDatePickerMode.date       


        // 01/01/1980 to 01/01/2000

        let calendar = Calendar.current
        var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
        minDateComponent.day = 01
        minDateComponent.month = 01
        minDateComponent.year = 1980

        let minDate = calendar.date(from: minDateComponent)
        print(" min date : \(minDate)")

        var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
       maxDateComponent.day = 01
        maxDateComponent.month = 01
        maxDateComponent.year = 2000

        let maxDate = calendar.date(from: maxDateComponent)
        print("max date : \(maxDate)")

        self.datePicker.minimumDate = minDate! as Date
        self.datePicker.maximumDate =  maxDate! as Date

}
Alvin George
  • 14,148
  • 92
  • 64
2

Swift 4.1

I have created my extension for all type of limit based on Calendar.Component

extension UIDatePicker {

    func setLimit(forCalendarComponent component:Calendar.Component, minimumUnit min: Int, maximumUnit max: Int) {

        let currentDate: Date = Date()
        var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)

        guard let timeZone = TimeZone(identifier: "UTC") else { return }
        calendar.timeZone = timeZone

        var components: DateComponents = DateComponents()
        components.calendar = calendar

        components.setValue(-min, for: component)
        if let maxDate: Date = calendar.date(byAdding: components, to: currentDate) {
            self.maximumDate = maxDate
        }

        components.setValue(-max, for: component)
        if let minDate: Date = calendar.date(byAdding: components, to: currentDate) {
            self.minimumDate = minDate
        }
    }

}

We can use this as following:

self.datePicker.setLimit(forCalendarComponent: .year, minimumUnit: 13, maximumUnit: 100)
g212gs
  • 863
  • 10
  • 26
1

Swift 4.0

UIDatePicker Extension

extension UIDatePicker {
    func set18YearValidation() {
        let currentDate: NSDate = NSDate()
        let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
        calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        let components: NSDateComponents = NSDateComponents()
        components.calendar = calendar as Calendar
        components.year = -18
        let maxDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
        components.year = -150
        let minDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
        self.minimumDate = minDate as Date
        self.maximumDate = maxDate as Date
    } }
Vishal Vaghasiya
  • 4,618
  • 3
  • 29
  • 40
PinkeshGjr
  • 8,460
  • 5
  • 41
  • 56
  • 1
    Hello, this code is works, but its not exactly swift4 syntax. NS are remnants of Obj-C era. Hereby at the bottom i provided correct version. – swift2geek Jan 10 '18 at 09:26
1

if you want to set current date as minimum value for date picker, use this line of code:

datePicker.minimumDate = Date()
Haseeb Javed
  • 1,769
  • 17
  • 20