年齢のみ
グレゴリオ暦の Calendar
クラスを使います。
let calendar = Calendar(identifier: .gregorian)
let birthDate = DateComponents(calendar: calendar, year: 1983, month: 4, day: 15).date!
let now = DateComponents(calendar: calendar, year: 2017, month: 1, day: 12).date!
let age = calendar.dateComponents([.year], from: birthDate, to: now).year!
age // -> 33
生まれてからの年と月と日数
赤ちゃんの年齢表記とかに使えそうですね。
let calendar = Calendar(identifier: .gregorian)
let birthDate = DateComponents(calendar: calendar, year: 2016, month: 1, day: 12).date!
let now = DateComponents(calendar: calendar, year: 2017, month: 1, day: 12).date!
let elapsedComps = calendar.dateComponents([.year, .month, .day], from: birthDate, to: now)
String(format: "生後%d年%dヶ月%d日", elapsedComps.year!, elapsedComps.month!, elapsedComps.day!) // -> 生後1年0ヶ月0日