How old are you now For those of you who can't answer quickly, we have created a program to calculate your birthday from your date of birth.
var birthdate = DateComponents(year: 1994, month: 10, day: 1)
var age: Int
//Calculate age
let calendar = Calendar.current
let now = calendar.dateComponents([.year, .month, .day], from: Date())
let ageComponents = calendar.dateComponents([.year], from: birthdate, to: now)
age = ageComponents.year!
It is also possible to convert from Date type to DateComponents type, so please apply if you want to manage birthday by Date. [Swift] Mutual conversion between Date and Date Components-Shime Saba Diary
I wanted to have my age entered automatically when I entered my birthday, but I gave up because didset was not called at the time of init.
class Person {
var age: Int?
var birthdate: DateComponents {
didSet(date){
//I won't be called! !! !!
let calendar = Calendar.current
let now = calendar.dateComponents([.year, .month, .day], from: Date())
let ageComponents = calendar.dateComponents([.year], from: date, to: now)
age = ageComponents.year!
}
}
init(date: DateComponents) {
birthdate = date
}
}
let hoge = Person(date: DateComponents(year: 1994, month: 10, day: 1))
Recommended Posts