先週/今週の任意の曜日の日付を取得する (e.g.今週の月曜日、先週の月曜日を取得する)
今週の月曜日を取得する。
this_day = Date.today this_monday = this_day - (this_day.wday - 1) # 今週の月曜日 last_monday = (this_day - (this_day.wday - 1)) - 7 # 先週の月曜日 --実行結果 [1] pry(main)> this_day = Date.today => Wed, 05 Dec 2012 [2] pry(main)> this_monday = this_day - (this_day.wday - 1) => Mon, 03 Dec 2012 [24] pry(main)> last_monday = (this_day - (this_day.wday - 1)) - 7 => Mon, 26 Nov 2012
ポイントは、wdayメソッドで日付を曜日分逆算すること。
Time#wdayメソッドの戻り値は、曜日を数値にした値です。
0(日曜日)〜6(土曜日)の値を返します。
[1] pry(main)> Time.now.strftime("%A") => "Wednesday" [2] pry(main)> Time.now.wday => 3
日曜日 => 0
月曜日 => 1
火曜日 => 2
水曜日 => 3
木曜日 => 4
金曜日 => 5
土曜日 => 6
応用編
今週の任意の曜日の取得
this_sunday = this_day - (this_day.wday) # 今週の日曜日 this_monday = this_day - (this_day.wday - 1) # 今週の月曜日 this_tuesday = this_day - (this_day.wday - 2) # 今週の火曜日 this_wednesday = this_day - (this_day.wday - 3) # 今週の水曜日 ← 現在 this_thursday = this_day - (this_day.wday - 4) # 今週の木曜日 ↓ 未来 (未来日でも、”-"して取得する) this_friday = this_day - (this_day.wday - 5) # 今週の金曜日 this_saturday = this_day - (this_day.wday - 6) # 今週の土曜日 --実行結果 [1] pry(main)> this_day = Date.today => Wed, 05 Dec 2012 [2] pry(main)> this_sunday = this_day - (this_day.wday) => Sun, 02 Dec 2012 [3] pry(main)> this_monday = this_day - (this_day.wday - 1) => Mon, 03 Dec 2012 [4] pry(main)> this_tuesday = this_day - (this_day.wday - 2) => Tue, 04 Dec 2012 [5] pry(main)> this_wednesday = this_day - (this_day.wday - 3) => Wed, 05 Dec 2012 [6] pry(main)> this_thursday = this_day - (this_day.wday - 4) => Thu, 06 Dec 2012 [7] pry(main)> this_friday = this_day - (this_day.wday - 5) => Fri, 07 Dec 2012 [8] pry(main)> this_saturday = this_day - (this_day.wday - 6) => Sat, 08 Dec 2012
先週の任意の曜日の取得
更にそこから - 7 すると先週の日付が求められる。
last_sunday = this_sunday - 7 last_monday = this_monday - 7 last_tuesday = this_tuesday - 7 last_wednesday = this_wednesday - 7 last_thursday = this_thursday - 7 last_friday = this_friday - 7 last_this_saturday = this_saturday - 7 --実行結果 [9] pry(main)> last_sunday = this_sunday - 7 => Sun, 25 Nov 2012 [10] pry(main)> last_monday = this_monday - 7 => Mon, 26 Nov 2012 [11] pry(main)> last_tuesday = this_tuesday - 7 => Tue, 27 Nov 2012 [12] pry(main)> last_wednesday = this_wednesday - 7 => Wed, 28 Nov 2012 [13] pry(main)> last_thursday = this_thursday - 7 => Thu, 29 Nov 2012 [14] pry(main)> last_friday = this_friday - 7 => Fri, 30 Nov 2012 [15] pry(main)> last_this_saturday = this_saturday - 7 => Sat, 01 Dec 2012 [16] pry(main)>