I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar() var dateComponentNow : NSDateComponents = calendar.components( NSCalendarUnit.CalendarUnitYear, fromDate: birthday, toDate: age, options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...; NSDate* now = [NSDate date]; NSDateComponents* ageComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:birthday toDate:now options:0]; NSInteger age = [ageComponents year];
Is there correct form better than this?
AGE=int((NOW - DOB)/365.25); This generally produces an accurate value for age, making it a nice solution for most applications. Depending on how leap years fall relative to the date of death and birth, the approximation could be off by as much as what is essentially two days over the interval.
age = INT((INTCK("month",dob,now) - (DAY(dob) > DAY(now)))/12); Essentially, this formula determines the number of months between DOB and NOW, decides whether to subtract 1, and then divides by 12 (the number of months in a year) to get number of years.
Simply by subtracting the birth date from the current date. This conventional age formula can also be used in Excel. The first part of the formula (TODAY()-B2) returns the difference between the current date and date of birth is days, and then you divide that number by 365 to get the numbers of years.
Age of a Person = Given date - Date of birth. Ron's Date of Birth = July 25, 1985. Given date = January 28, 2021. Years' Difference = 2020 - 1985 = 35 years.
You get an error message because 0
is not a valid value for NSCalendarOptions
. For "no options", use NSCalendarOptions(0)
or simply nil
:
let ageComponents = calendar.components(.CalendarUnitYear, fromDate: birthday, toDate: now, options: nil) let age = ageComponents.year
(Specifying nil
is possible because NSCalendarOptions
conforms to the RawOptionSetType
protocol which in turn inherits from NilLiteralConvertible
.)
Update for Swift 2:
let ageComponents = calendar.components(.Year, fromDate: birthday, toDate: now, options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date
and Calendar
are used:
let now = Date() let birthday: Date = ... let calendar = Calendar.current let ageComponents = calendar.dateComponents([.year], from: birthday, to: now) let age = ageComponents.year!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With