2014-01-23 94 views
2

的第一beginning_of_week如果我想知道在一個月哪一天過去曾是第一個星期一,也就是一個月的第一beginning_of_week,我可以開始通過了解什麼最後:獲取某個月

Date.current - 1.month 

而且還有得到那個月的開始:

(Date.current - (1.month)).beginning_of_month 

但是我怎麼能有效地得出那個月第一週開始的日期?

回答

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

這麼優雅讓我微笑(: – Numbers

0

可以手動

date = (Date.current - (1.month)).beginning_of_month 
if date.wday != 1 
    date = date.end_of_week 
    date += date.day 
end 
2

做嘗試

date = (Date.current - (1.month)).beginning_of_month  
date = date.next_week unless date.monday? 
+0

但我猜不正確如果'beginning_of_month' =='一天beginning_of_week'? – Numbers

+1

這是真的 - 需要額外檢查,我已更新示例代碼。 – eugen

1
start = Date.current.beginning_of_month 
start.upto(start.next_week).find(&:monday?) 
#=> Mon, 06 Jan 2014 
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 
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")