[Swift]Dateの年を取得するには?

Swift

どうも、ちょげ(@chogetarou)です。

Dateの年を取得する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Dateの年を取得するには、Calendarを使います。

まず、Caledar.current.component()を呼び出します。

そして、componentの第1引数に「.year」、第2引数「from」に対象のDateを指定します。

let year = Calendar.current.component(.year, from: date)

Calendar.current.componetによって、対象のDateの年を取得することが出来ます。

使用例

let today = Date()
let year = Calendar.current.component(.year, from: today)

print(today)
print(year)

オススメの記事

[Swift]日付の曜日を取得するには?

[Swift]乱数を生成するには?

[Swift]文字列の先頭から文字数分を取り出すには?

コメント

タイトルとURLをコピーしました