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
Convert facebook birthday to age swift
func yearsBetween(date1: Date, date2: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.year], from: date1, to: date2)
return components.year ?? 0
}
// Get Age
let dateString = "01/12/1990"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let date1 = dateFormatter.date(from: dateString)
let date2 = Date()
let age = self.daysBetween(date1:date1!, date2:date2)
Hope it will help you.
Get age from range in SwiftUI DatePicker
You can use .onChange
to track the changes in birthDate and do the calculation inside the closure.
Note: SwiftUI runs this closure in main thread
. so If you want to do expensive work there you should dispatch to a background Queue
to let the UI run smoothly.
struct ContentView: View {
@State private var birthDate = Date()
@State private var age: DateComponents = DateComponents()
var body: some View{
VStack {
Form {
DatePicker("Birth date:", selection: $birthDate, in: ...Date(), displayedComponents: .date).datePickerStyle(WheelDatePickerStyle()).font(.title)
}.onChange(of: birthDate, perform: { value in
age = Calendar.current.dateComponents([.year, .month, .day], from: birthDate, to: Date())
})
Text("Age-> Years:\(age.year ?? 0) Months:\(age.month ?? 0) Days\(age.day ?? 0)")
}
}
}
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".
Calculating Age: Ambiguous reference to member on DateComponents
You have a few issues in your code
- You should use
Date
, notNSDate
in Swift birthdayDate
is aString
, but thefrom:
parameter needs to be an instance ofDate
- The components parameter needs to be a set.
Correcting these gives you:
@objc func dateChanged(datePicker: UIDatePicker) {
let birthdayDate = datePicker.date
let myCalendar = Calendar(identifier: .gregorian)
let dmy = myCalendar.dateComponents([.day, .month, .year], from: Date())
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
inputTextField.text = dateFormatter.string(from: birthdayDate)
let now = Date()
let ageComponents = myCalendar.dateComponents([.year], from: birthdayDate, to: now)
let age = ageComponents.year!
label.text = "\(age)"
view.endEditing(true)
}
Related Topics
How to Use Attributed String in Swiftui
How to Compare One Value Against Multiple Values - Swift
How to Round a Double to the Nearest Int in Swift
How to Apply the Type to a Nsfetchrequest Instance
Swift Equality Operator on Nested Arrays
Does Swift Have Documentation Generation Support
Whither Dispatch_Once in Swift 3
Getting the Decimal Part of a Double in Swift
Swift 2 ( Executefetchrequest ): Error Handling
Realitykit VS Scenekit VS Metal - High-Quality Rendering
Precision String Format Specifier in Swift
How to Provide a Localized Description With an Error Type in Swift