2013-05-06 38 views

risposta

6

Questo funziona in 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)> 

In Rails c'è beginning_of_week:

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

'beginning_of_week' è un modo veramente interessante/conciso per risolvere questo problema. Grande idea! – Shpigford

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

Questo ... è ... brillante! – MrYoshiji

0

Abbastanza semplice, con Date:

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

È possibile anche ottenere l'ultimo giorno della settimana della vostra scelta di questo tipo (qui senza la gestione degli errori):

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

Se si sta bene con l'utilizzo di un altro gioiello, vi consiglio Chronic.

Con esso, è possibile ottenere Mercoledì scorso facendo:

Chronic.parse('last Wednesday') 
2

Il modo più semplice (per me) è:

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

Bel colpo. –

Problemi correlati