LoginSignup
4
5

More than 5 years have passed since last update.

曜日から次の曜日の日付を取得する

Posted at

なかなか事例がないと思いますが、次の日曜日を取得する必要があったので、書いてみました。

// 例)次の日曜日を取得
let weekday : Int = 0

let cal = Calendar(identifier: Calendar.Identifier.gregorian)

let comp : DateComponents = cal.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: Date())
var fixComp : DateComponents = DateComponents()

//  マイナスになった場合は7を足して、調整する
let addDay : Int = (weekday - comp.weekday!) < 0 ? (weekday - comp.weekday!) + 7 : (weekday - comp.weekday!)

// 計算した日付を足して、次の曜日が来る日に調整
fixComp.day = addDay

// 調整を基に日付を取得
let date : Date = cal.date(byAdding: fixComp, to: Date())!

なお、「次の」ではなく「その週の」曜日の日付を取得したい場合は、

let addDay : Int = (weekday - comp.weekday!) < 0 ? (weekday - comp.weekday!) + 7 : (weekday - comp.weekday!)



let addDay : Int = (weekday - comp.weekday!)

このように変更すれば取得することができます。

そして例では今を基準にしていますが、Date()のところの箇所を過去・未来の日付にすれば、基準となる日を変更することができます。

// 例)今から2週間後を基準値に設定
let futureDate : Date = Date(timeIntervalSinceNow:60*60*24*7*2)
let weekday : Int = 0

let cal = Calendar(identifier: Calendar.Identifier.gregorian)

let comp : DateComponents = cal.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: futureDate)
var fixComp : DateComponents = DateComponents()

let addDay : Int = (weekday - comp.weekday!)

fixComp.day = addDay

// 2週間後の週の中の日曜日の日付を取得
let date : Date = cal.date(byAdding: fixComp, to: futureDate)!

参考:http://program.station.ez-net.jp/special/handbook/objective-c/nsdate/next-weekday.asp

4
5
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
4
5