12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift3 で生年月日から現在の年齢を取得する

Last updated at Posted at 2017-01-11

年齢のみ

グレゴリオ暦の 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日
12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?