如果我想知道上个月的哪个日期是第一个星期一,即月份的第一个beginning_of_week
,我可以先了解最后的情况:
Date.current - 1.month
并且也是那个月的开头:
(Date.current - (1.month)).beginning_of_month
但是,我怎样才能有效地了解当月第一周开始的日期?
答案 0 :(得分:4)
您可以执行以下操作:
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
我的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
答案 1 :(得分:2)
尝试
date = (Date.current - (1.month)).beginning_of_month
date = date.next_week unless date.monday?
答案 2 :(得分:1)
start = Date.current.beginning_of_month
start.upto(start.next_week).find(&:monday?)
#=> Mon, 06 Jan 2014
答案 3 :(得分:1)
您可以使用的方法是
date_in_last_month = Time.now - 1.month
beginning_of_month = date_in_last_month.beginning_of_month
beginning_of_week = beginning_of_month.beginning_of_week
if beginning_of_week < beginning_of_month
beginning_of_week + 7.days
else
beginning_of_week
end
有点长的啰嗦,但有一些代码高尔夫,我认为它可能会做你想要的。
如果您拥有'慢性'宝石,您可以执行以下(credit)
require 'chronic'
date_start = Chronic.parse("Monday of first week of February")
答案 4 :(得分:0)
你可以手动完成
date = (Date.current - (1.month)).beginning_of_month
if date.wday != 1
date = date.end_of_week
date += date.day
end
答案 5 :(得分:0)
试试这个:
def first_monday(months_before)
start_of_month = months_before.months.ago.beginning_of_month.to_date
return start_of_month if start_of_month.monday?
start_of_month += 8 - start_of_month.cwday
end
first_monday 5
=> Mon, 05 Aug 2013