Reputation: 1593
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.
Upvotes: 0
Views: 3550
Reputation: 1
Firstly, you have to get parts of date as Int type using Calendar component methods:
// Current date
let currentDate = Date()
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: currentDate) //year: Int
let currentMonth = calendar.component(.month, from: currentDate) //month: Int
let currentDay = calendar.component(.day, from: currentDate) //day: Int
// DatePicker's date
let yearFromDatePicker = calendar.component(.year, from: datePicker.date) //year: Int
let monthFromDatePicker = calendar.component(.month, from: datePicker.date) //month: Int
let dayFromDatePicker = calendar.component(.day, from: datePicker.date) //day: Int
and then you can compare parts of the date with each other based on your conditions.
Upvotes: 0
Reputation: 50089
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*/
}
}
Upvotes: 0
Reputation: 236305
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
Upvotes: 0
Reputation: 11201
Use this function to compare date
func compareDate(date1: NSDate!, toDate date2: NSDate!, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult
see this question
Upvotes: 0