benji
benji

Reputation: 21

calculate age with textfield swift 4

I wanna calculate someones age who ist typed his birthdate in a textfield.

 @IBAction func profilSettings(_ sender: AnyObject) {
    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)        
}

Errors:

Cannot assign to immutable expression of type "NSCalendar?.Type"

Ambigous references to member "components(_:from:)"

Upvotes: 0

Views: 1811

Answers (2)

iOS Geek
iOS Geek

Reputation: 4855

Here you can use this code to get Age from a entered Date String

/// DOB String Entered
let dob : String = "05-31-1996"

/// Format Date
var myFormatte = DateFormatter()
myFormatte.dateFormat = "MM-dd-yyyy"

/// Convert DOB to new Date
var finalDate : Date = myFormatte.date(from: dob)!

/// Todays Date
let now = Date()
/// Calender
let calendar = Calendar.current

/// Get age Components
let ageComponents = calendar.dateComponents([.year], from: finalDate, to: now)
print("Age is \(ageComponents.year!)") /// Output 21

Output Screenshot

enter image description here

Upvotes: 2

vadian
vadian

Reputation: 285150

Two issues:

  • Use Calendar rather than NSCalendar

    let cal = Calendar:identifier: .gregorian)!
    
  • The error occurs, because you use the type Calendar instead of the instance cal and the API of Calendar is dateComponents(...

    let year = cal.dateComponents([.year], from: dob!, to: now)
    

There are more issues:

  • dob must be a Date instance, the birthday.
  • The line let age = (year!) - Int(y1)! is wrong, the expected result is let age = year.year!

Upvotes: 0

Related Questions