Friday, February 24, 2017

Swift 3 Getting Age from DOB

If we have a functionality like user enters his/her DOB date and we need to calculate age or we are getting DOB string from service response and we need to calculate user’s age, Welcome to this post and see how to calculate age based on DOB.

In this post I am going to explain how to calculate age If we have a DOB string in
yyyy-MM-dd format.


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

 let strDOB = "1986-06-28" 

 let ageComponents = strDOB.components(separatedBy: "-") //["1986", "06", "28"]

 let dateDOB = Calendar.current.date(from: DateComponents(year:  
                                    Int(ageComponents[0]), month: Int(ageComponents[1]), day: 
                                    Int(ageComponents[2])))!   
                                                                 //Jun 28, 1986, 12:00 AM

 let myAge = dateDOB.age  //30


I have taken a simple Date extension where I am having age property which gives me number of years from current year technically. from is DOB date and to is current date.

My DOB string(1986-06-28), I am splitting by separator '-' and getting year, month and date strings, converting them to Ints and passing to Calendar's current date from components method to convert it to Date object and calling age property in my extension to get number of years gap from DOB date to current date which is technically user's age.

Hope this post is useful. Feel free to comment incase of any queries.


1 comment: