Calculate age from birthday with 4 lines of Swift ~ How old are you now? To you who became ~

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


bonus

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))

I felt that the didSet of the member variable (property) was not called when deiniting in Swift – su- tech blog

Recommended Posts

Calculate age from birthday with 4 lines of Swift ~ How old are you now? To you who became ~
To you who will become the leader of the development team from now on-Minimum standardization-
[swift5] How to change the color of TabBar or the color of item of TabBar with code
[Java] How to calculate age using LocalDate
How to call Swift 5.3 code from Objective-C
How to get the ID of a user authenticated with Firebase in Swift
Are you still exhausted with CollectionView? CompositionalLayout starting from iOS12 ~ From implementation to design ~