0

I am trying calculate the age from birthday Date in Swift with this function: (want to write in a textField and pass this data from VC in a Label)

{
var a = self.dob.text
        var c = a!.components(separatedBy: "-")
        var y1 = c[2]
        let cal = NSCalendar? = NSCalendar(calendarIdentifier: .gregorian)
        let now = Date()
        let year = Calendar.components(.year, from: dob!, to: now, options: [])
        let age = (year!) - Int(y1)!
        self.myage.text = String(age)

}

But I get an error cannot assign NSCalendar?.Type, but I don't know why get this error (its my first time coding)

Michał Zalewski
  • 3,123
  • 2
  • 24
  • 37
Ben
  • 11
  • 1
  • 1
  • There are errors on every line and it seem you don't know what you are doing. Your `year` is actually the `age`. – Sulthan Apr 22 '18 at 16:57
  • Duplicate of https://stackoverflow.com/questions/49965061/calculate-age-with-textfield-swift-4 . Different user, same question – vadian Apr 22 '18 at 19:52
  • This one is useful of you : - https://stackoverflow.com/questions/25232009/calculate-age-from-birth-date-using-nsdatecomponents-in-swift – Gaurav Patel Apr 23 '18 at 12:34

3 Answers3

2

You have a few problems in your code. First there is a type as already mentioned by Qi Hao, second you are passing dob is a text field you and Calendar components method expects two dates, so you should first parse the text field date then you can get the year component difference from input date and now:

Playground Testing

let dob = UITextField()
dob.text = "03-27-2002"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: dob.text!) {
    let age = Calendar.current.dateComponents([.year], from: date, to: Date()).year!
    print(age)  // 16
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0
  func age(on baseDate: DateComponents) -> Int {
    if baseDate.month > month {
      return baseDate.year - year
    }
    if baseDate.month == month && baseDate.day >= day {
      return baseDate.year - year
    }
    return baseDate.year - year - 1
  }
hojin
  • 1,221
  • 14
  • 16
0

try this:

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!
}