2013-05-06 70 views

回答

6

此作品在Ruby中:

require 'date' 

def last_wednesday(date) 
    date - (date.wday - 3) % 7 
end 

last_wednesday(Date.today) 
# => #<Date: 2013-05-01 ((2456414j,0s,0n),+0s,2299161j)> 

在Rails有beginning_of_week

Date.today.beginning_of_week(:wednesday) 
# => Wed, 01 May 2013 
+1

'beginning_of_week'是一個非常有趣/簡潔的方法來解決這個問題。好想法! – Shpigford 2013-05-07 13:36:42

8
time = Time.now 
days_to_go_back = (time.wday + 4) % 7 
last_wed = days_to_go_back.days.ago 
+0

這...是... ...輝煌! – MrYoshiji 2013-05-06 21:10:17

0

非常簡單與Date

require 'date' 
today = DateTime.now.to_date 
last_wednesday = today.downto(today - 6).select { |d| d.wednesday? } 

你甚至可以讓你選擇的是這樣的最後一個工作日(這裏沒有錯誤處理):

def last_weekday(weekday) 
    today = Time.now.to_date 
    today.downto(today-6).select do |d| 
    d.send((weekday.to_s + "?").to_sym) 
    end 
end 
2

如果你是沒事用另一顆寶石,我建議Chronic

有了它,你可以通過執行獲得最後一個星期三:

Chronic.parse('last Wednesday') 
2

最簡單的方式(對我來說)是:

require 'date' 
date = Date.today 
date -= 1 until date.wednesday? 
+0

相當不錯的鏡頭。 – 2013-05-06 23:59:17