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

Swift

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

日付の曜日を取得する方法を紹介します。

スポンサーリンク

方法

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

日付の曜日を取得するには、Calendarを使います。

まず、「Clendar.current.component()」を呼び出します。

そして、componentの第1引数に「.weekday」、第2引数「from」に日付を指定します。

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

Calendar.current.component(.weekday, from: date)は、引数「from」に指定した日付の曜日を数値として返します。

Calendar.current.component(.weekday, from: date)で返す数値は、月曜日が1、火曜日が2、・・・、日曜日が7のようになっています。

使用例

var currentDate = Date()
let weekDay = Calendar.current.component(.weekday, from: currentDate)

print(weekDay)

コメント

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