获取特定月份的第一个 begin_of_week

Fel*_*ger 2 ruby ruby-on-rails date ruby-on-rails-4

如果我想知道上个月的第一个星期一是什么日期,即本月的第一个beginning_of_week,我可以从了解最后一个是什么开始:

Date.current - 1.month
Run Code Online (Sandbox Code Playgroud)

以及获得那个月的开始:

(Date.current - (1.month)).beginning_of_month
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能有效地获得该月第一周的开始日期?

MrY*_*iji 5

您可以执行以下操作:

date = (Date.current - (1.month)).beginning_of_month
date += 1.days until date.wday == 1 # wday 1 is monday
# why you english people consider Sunday as the first day of the week ?! ahah
Run Code Online (Sandbox Code Playgroud)

我的 IRB 控制台中的输出:

1.9.3p489> date = (Date.current - (1.month)).beginning_of_month
# => Sun, 01 Dec 2013 
1.9.3p489> date += 1.days until date.wday == 1
# => nil 
1.9.3p489> date
# => Mon, 02 Dec 2013 
Run Code Online (Sandbox Code Playgroud)