如何使用Ruby(和Rails,如果有相关的辅助方法),我将如何获得最近发生的星期三?
最终需要实际日期(2013年5月1日)。
答案 0 :(得分:8)
time = Time.now
days_to_go_back = (time.wday + 4) % 7
last_wed = days_to_go_back.days.ago
答案 1 :(得分: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
答案 2 :(得分:2)
答案 3 :(得分:2)
最简单的方法(对我而言)是:
require 'date'
date = Date.today
date -= 1 until date.wednesday?
答案 4 :(得分: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