54
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

今週の月曜日、先週の月曜日、来週の月曜日を取得する

今週の月曜日、先週の月曜日、来週の月曜日を取得する

Ruby メソッドを使う

コード

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
=> Thu, 10 Jan 2013
[2] pry(main)> this_monday = this_day - (this_day.wday - 1)
=> Mon, 07 Jan 2013
[3] pry(main)> last_monday = (this_day - (this_day.wday - 1)) - 7
=> Mon, 31 Dec 2012

Rails active_support のメソッドを使う

コード

Date.today.beginning_of_week # 今週の月曜日
(Date.today - 1.week).beginning_of_week # 先週の月曜日
# Date.todayではなく、Time.nowでもOK

実行結果

[1] pry(main)> Date.today
=> Thu, 10 Jan 2013
[2] pry(main)> Date.today.beginning_of_week
=> Mon, 07 Jan 2013
[3] pry(main)> Date.today.beginning_of_week - 1.week
=> Mon, 31 Dec 2012

active_support 追記

prev_weekメソッド

コード
prev_week
0.days.ago.prev_week # 先週の月曜日
0.days.ago.prev_week(:sunday) # 先週の日曜日
0.days.ago.prev_week(:friday) # 先週の金曜日
実行結果
[1] pry(main)> 0.days.ago.prev_week
=> 2012-12-31 00:00:00 +0900
[2] pry(main)> 0.days.ago.prev_week(:sunday)
=> 2013-01-06 00:00:00 +0900
[3] pry(main)> 0.days.ago.prev_week(:friday)
=> 2013-01-04 00:00:00 +0900

next_weekメソッド(来週を取得したい!)

コード
next_week
0.days.ago.next_week # 来週の月曜日
0.days.ago.next_week(:sunday) # 来週の日曜日
0.days.ago.next_week(:friday) # 来週の金曜日
実行結果
[1] pry(main)> 0.days.ago.next_week
=> Mon, 14 Jan 2013 00:00:00 JST +09:00
[2] pry(main)> 0.days.ago.next_week(:sunday)
=> Sun, 20 Jan 2013 00:00:00 JST +09:00
[3] pry(main)> 0.days.ago.next_week(:friday)
=> Fri, 18 Jan 2013 00:00:00 JST +09:00
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
54
Help us understand the problem. What are the problem?