0

In my app a user can select whether or not they are under 18 or over 18 years of age. The user enters their Date of Birth using a Date Picker. I need to make a function that will compare the current date in MM/DD/YYYY format to the DatePicker date to see if the user's entered age is over 18.

My current function for setting the DatePicker text to the associated textfield is:

func updatePicker() {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    dob.text = dateFormatter.stringFromDate(datePickerView.date)
}

When the user tries to go the next page, the form is validated which is when I need to compare the dates and display the alert if they're under 18.

Just not sure where to start with date string evaluation.

matcartmill
  • 1,423
  • 2
  • 18
  • 36

3 Answers3

0

Use this function to compare date

func compareDate(date1: NSDate!, toDate date2: NSDate!, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult

see this question

Community
  • 1
  • 1
Teja Nandamuri
  • 10,632
  • 6
  • 54
  • 95
0

don't convert the date to text and later convert the text to the date again. just keep the date from the datePicker around till you need it for the validation.

have a member variable var selectedDate : NSDate?

then later to check if older than 18 just do

if let userDate=self.selectedDate {
    if(NSDate().timeIntervalSinceDate(userDate) >= (568024668 /*18 years in seconds*/) {
        .... /*is 18*/
    }
}
Daij-Djan
  • 47,307
  • 15
  • 99
  • 129
  • This is a very simple solution, however one issue I found is that if today is the user's 18th birthday it's saying that they're still under 18. It seems that it needs to be -/+ 1 day, but I'm not sure how I feel about modifying that just for this to work. – matcartmill Feb 22 '15 at 23:03
  • Oh I know that, haha. I just don't want someone being to exploit this. Ill give it a shot and see how it evaluates under a few tests. – matcartmill Feb 22 '15 at 23:08
  • this is wrong though.. don't do -1 day .. what'd you want to o than is round the current Date down to midnight -- use NSDateComponents – Daij-Djan Feb 22 '15 at 23:08
0

You can use NSCalendar components method and extract NSCalendarUnit.CalendarUnitYear difference from two dates:

extension NSDate {
    var is18yearsOld:Bool {
        return NSDate().yearsFrom(self) > 18
    }
    func yearsFrom(date:NSDate)   -> Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear, fromDate: date, toDate: self, options: nil).year }
}

let dob1 = NSCalendar.currentCalendar().dateWithEra(1, year: 1970, month: 3, day: 27, hour: 7, minute: 19, second: 26, nanosecond: 0)!
let dob2 = NSCalendar.currentCalendar().dateWithEra(1, year: 2000, month: 3, day: 27, hour: 7, minute: 19, second: 26, nanosecond: 0)!
let is18years1 = dob1.is18yearsOld    // true
let is18years2 = dob2.is18yearsOld    // false
Leo Dabus
  • 198,248
  • 51
  • 423
  • 494