54
53

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-01-09

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

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
54
53
4

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
54
53

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?