如何找到迄今为止一周或一个月内的日期。
days_for_week should return 19,20,21 (assuming current date is 21st)
days_for_month should return 1..21 (assuming current date is 21st)
如何找到迄今为止一周或一个月内的日期。
days_for_week should return 19,20,21 (assuming current date is 21st)
days_for_month should return 1..21 (assuming current date is 21st)
首先,您可以使用Time.now.wday
获取当前工作日,然后减去这将为您提供本周开始的日期。
对于第二个,它更简单,每个月都以 开头1st
,对吗?
假设我正确阅读了您的问题...
第二个很简单:
def days_for_month
1..Date.today.day
end
第一个需要一个小算法才能追溯到星期六:
def days_for_week
days = []
day = Date.today
until day.saturday?
days.unshift(day.day)
day -= 1
end
days
end
主动支持提供了很多有用的方法,例如at_beginning_of_week、at_end_of_week、 at_beginning_of_month 等。
> Date.today.at_beginning_of_week
=> Mon, 20 May 2013
对于这种特殊情况,您可以这样做
> (Date.today.at_beginning_of_week..Date.today).map &:day
=> [20, 21]
相似地
> (Date.today.at_beginning_of_month..Date.today).map &:day
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
或者干脆
> 1..Date.today.day