Swiftで遊ぼう! - 963 - dateComponentsを使いこなせ!
- Swiftで遊ぼう!の前書き-> Life-LOG OtherSide
- 初心者はここから!-> 50オヤジでもできるiOS開発
- 私の本業、オフィシャルなブログ-> Life-LOG
- Swift 3 対応
年齢計算をする場合、Calendarクラスを使って、DateクラスからDateComponentsクラスに変換して日付計算をするのが基本のようです。Dateクラスだけで日付の計算はできないからです。Dateクラスは日付にかかわる「単位」と考えるといいでしょう。
日付を引き算させるメソッドが次のものです。
func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents
ここでCalendar.Componentでどの情報を扱うか指定します。そして2つのDate型の差を得るメソッドになります。これでComponentの「.year」だけ扱えば年齢が得られます。
じゃあどうすべきか?指定された日付(誕生日)のDateクラスインスタンス作成をするためにDateクラスのイニシャライザーは対応していません。Dateクラスインスタンスを作るためにCalendarクラスかDateFormatterを使う必要があります。日付の計算をさせるのでCalendarクラスを利用するのが望ましいということですね。
// まずカレンダークラスインスタンスを作ります。 let myCalendar = Calendar(identifier: .gregorian) // Dateクラスをインスタンス化するためにDateComponentsクラスが必要 // なので必要な情報を用意します。 let myBirthdayComponents = DateComponents(calendar: myCalendar, timeZone: nil, era: nil, year: 1965, month: 4, day: 1, hour: nil, minute: nil, second: nil, nanosecond: nil, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil) // 上記のDateComponentsクラスインスタンスを使ってDateクラスの // インスタンスを作ります。 let myBirthday = myCalendar.date(from: myBirthdayComponents) // Date型イニシャライザーを使って現在時刻を使ってDateクラスの // インスタンを作れます。 let currentDate = Date() // そして2つのDateクラスインスタンスの差を次のように得ます。 let myAge = myCalendar.dateComponents([.year], from: myBirthday!, to: currentDate).year! // myAgeはInt型なので「My age is 51.」と表示されます。 print("My age is \(myAge).")