Skip to content

Instantly share code, notes, and snippets.

@kawamurayuto
Last active January 11, 2017 16:50
Show Gist options
  • Select an option

  • Save kawamurayuto/e1aa504891cbf8469842783e69b2533c to your computer and use it in GitHub Desktop.

Select an option

Save kawamurayuto/e1aa504891cbf8469842783e69b2533c to your computer and use it in GitHub Desktop.
Swift3 で生年月日から現在の年齢を取得する ref: http://qiita.com/kawamurayuto/items/6297046603b6d088434e
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日
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment