swift nsdatecomponents

Calcule la edad a partir de la fecha de nacimiento utilizando NSDateComponents en Swift



(4)

Creo este método, es muy fácil, simplemente ponga la fecha de cumpleaños en el método y esto devolverá la edad como una Int.

Swift 3

func calcAge(birthday: String) -> Int { let dateFormater = DateFormatter() dateFormater.dateFormat = "MM/dd/yyyy" let birthdayDate = dateFormater.date(from: birthday) let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian) let now = Date() let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: []) let age = calcAge.year return age! }

Swift 2

func calcAge(birthday: String) -> Int{ let dateFormater = NSDateFormatter() dateFormater.dateFormat = "MM/dd/yyyy" let birthdayDate = dateFormater.dateFromString(birthday) let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) let now: NSDate! = NSDate() let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: []) let age = calcAge.year return age }

Uso

print(calcAge("06/29/1988"))

Estoy intentando calcular la edad de fecha de cumpleaños en Swift con esta función:

var calendar : NSCalendar = NSCalendar.currentCalendar() var dateComponentNow : NSDateComponents = calendar.components( NSCalendarUnit.CalendarUnitYear, fromDate: birthday, toDate: age, options: 0)

Pero me sale un error Extra argument toDate in call

En el objetivo c, este era el código, pero no sé por qué se produce este error:

NSDate* birthday = ...; NSDate* now = [NSDate date]; NSDateComponents* ageComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:birthday toDate:now options:0]; NSInteger age = [ageComponents year];

¿Hay forma correcta mejor que esto?


Esto está funcionando en swift 3 para mí ..

let now = NSDate() let calendar : NSCalendar = NSCalendar.current as NSCalendar let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: []) let age = ageComponents.year! ageCalculated.text = String(age)

Gracias a @Martin R


Esto funciona para Swift 3

let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))! let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month! let years = myAge / 12 let months = myAge % 12 print("Age : /(years)./(months)")


Recibirá un mensaje de error porque 0 no es un valor válido para NSCalendarOptions . Para "sin opciones", use NSCalendarOptions(0) o simplemente nil :

let ageComponents = calendar.components(.CalendarUnitYear, fromDate: birthday, toDate: now, options: nil) let age = ageComponents.year

(Es posible especificar nil porque NSCalendarOptions ajusta al protocolo RawOptionSetType que a su vez se hereda de NilLiteralConvertible ).

Actualización para Swift 2:

let ageComponents = calendar.components(.Year, fromDate: birthday, toDate: now, options: [])

Actualización para Swift 3:

Suponiendo que se utilicen la Date y el Calendar Swift 3 tipos:

let now = Date() let birthday: Date = ... let calendar = Calendar.current let ageComponents = calendar.dateComponents([.year], from: birthday, to: now) let age = ageComponents.year!