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