jenny sam
jenny sam

Reputation: 191

Swift: Cannot handle the date function properly while subtracting the Date:

I am trying to set the minimum date to 1987 from present date. I have successfully implemented this but i cannot figure out why the Past months from present months are fields are disable.

Like Todays current month is August then if i select 1987 as the year then Months before August are disabled.I cannot figure out why is this happening?

This is my code to calculate max and min dates:

    let currentDate: NSDate = NSDate()

    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    // let calendar: NSCalendar = NSCalendar.currentCalendar()

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

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

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


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


    print("minDate is the: \(minDate)")
    print("maxDate is the: \(maxDate)")

It is working fine for the dates after 1987.I want to enable all the months and days even for 1987

Upvotes: 1

Views: 319

Answers (2)

Duncan C
Duncan C

Reputation: 131501

What it's doing makes perfect sense. If you build a date that's August 5, 1987, and install it as the minimum date for a date picker, you're telling the date picker that the user should not be able to select a date earlier than that. If the user selects the year 1987, then a month earlier than August is less than the specified minimum date. It won't let the user pick a date before August 5, 1987.

Edit

If you want to allow any date in 1987, you should make the minimum date in the date picker Jan 1 1987. You could do that with date components by setting the month and day both to 1.

Upvotes: 2

vadian
vadian

Reputation: 285280

If you want to subtract 30 years from today and get the beginning of the year (January 1st) use

let calendar = Calendar.current
var components = calendar.dateComponents([.year], from: Date())
components.year! -= 30
let minDate = calendar.date(from: components)!

It extracts only the year component from the current date and subtracts 30. As month and day are not specified a value of 1 is considered respectively.

The code is written in Swift 3, it's highly recommended to update. Swift 4 is coming up.

Upvotes: 2

Related Questions