When retrieving birthday from the Facebook SDK i get this string "01/12/1990".
My question is, how would you convert the birthday into the age of the user using this string?
When retrieving birthday from the Facebook SDK i get this string "01/12/1990".
My question is, how would you convert the birthday into the age of the user using this string?
Swift 4
My use case is also for Facebook and I have used UserDefaults to store the birthdate. The below function will retrieve birthdate from UserDefaults, as returned by the graphRequest which is in the same format as your Date. The function will return an Integer with the user's age.
func getAgeFromBirthdate() -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let birthday = UserDefaults.standard.object(forKey: "birthday")
let birthdayString = birthday as! String
let birthdate = dateFormatter.date(from: birthdayString)
let currentDate = Date()
let calendar: Calendar = Calendar(identifier: .gregorian)
let age = calendar.component(.year, from: birthdate!).distance(to: calendar.component(.year, from: currentDate))
return age
}
You can do a little more Google before ask, also you may find these answers helpful:
How do you create a swift Date object
Calculate age from birth date using NSDateComponents in Swift
func calcAge(birthday:String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now as Date, options: [])
let age = calcAge.year
return age!
}
usage:
print(calcAge(birthday: "01/12/1990"))
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.