Calculate Age with Textfield Swift 4

Birthday date in UITextField and check age

First, to get the date you want from the DatePicker, the sender is a type of UIDatePicker, not UITextField claimed in your method input.

Second, refer to this answer, you can get the age by

let ageComponents = calendar.components(.Year, fromDate: sender.date, toDate: NSDate(), options: [])

EDIT

You added a selector method named datePickerValueChanged, but the the action is named tfDateNaissanceChanged. Or I should put it in this way that you don't need to listen to TextView value changed, just need to implement the method for DataPicker value changed.

How do I print the age based on the selected date picker on a text field?

Try changing your code as follows - using #selector() and exposing your function to @objc

datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)

@objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}

To answer your second question of how to get the age:

let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: sender.date, to: Date())
if let age = ageComponents.year {
print(age)
}

Calculating Age From Date Picker Swift 3

Simple solution, ignore day and month:

let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: dateOfBirth, to: Date())
let age = ageComponents.year!

txtAgeConfirmation.textColor = age < 21 ? .red : .black

Or if you want to ignore the time

let ageComponents = calendar.dateComponents([.year], from: calendar.startOfDay(for: dateOfBirth), to: calendar.startOfDay(for: Date()))

In Swift 3 there are less question and exclamation marks by using native Calendar struct.

The age exclamation mark after year is absolutely safe because the year component is clearly specified.

Calculate age from birth date using NSDateComponents in Swift

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!

Calculate age from birth date

update: Xcode 11 • Swift 5.1

You can use the Calendar method dateComponents to calculate how many years from a specific date to today:

extension Date {
var age: Int { Calendar.current.dateComponents([.year], from: self, to: Date()).year! }
}


let dob = DateComponents(calendar: .current, year: 2000, month: 6, day: 30).date!
let age = dob.age // 19

Sample Image

How do I get the age after using a date picker?

This will work fine for u

var birthday: NSDate = .....  //date that comes from date picker
var now: NSDate = NSDate()
var ageComponents: NSDateComponents = NSCalendar.currentCalendar().components(.Year, fromDate: birthday, toDate: now, options: 0)
var age: Int = ageComponents.year()

If u want to formate date you can use DateFormatter

Ex.

let usDateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy".

let gbDateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"

formatter.dateFormat = usDateFormat
let usSwiftDayString = formatter.stringFromDate(swiftDay)
// usSwiftDayString now contains the string "06/02/2014".

formatter.dateFormat = gbDateFormat
let gbSwiftDayString = formatter.stringFromDate(swiftDay)
// gbSwiftDayString now contains the string "02/06/2014".

SwiftUI - I want to display birthdate(only day, month and year) after i get it out of the `Datepicker`

A quick and simple approach is to use DateFormatter and luckily SwiftUI Text View supports it:

The code would look like this:

// 1. Create a Dateformatter
var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long

return dateFormatter
}()

  1. Change : Text("\(birthdate)") to Text(birthdate, formatter:dateFormatter)

You can play with dateFormatter.dateStyle value to get the one you like, check out Set a datestyle in Swift, to read more about how you can play with it



Related Topics



Leave a reply



Submit