我想找到1月后的第一个工作日,这个工作日也恰好落在Ruby的工作日,如下所示:
Min ( DayOfMonth in (2...8) && DayOfWeek in ( monday ... friday ) )
我如何恰当地说明这一点?
答案 0 :(得分:2)
我们可以简单地从所需月份的第二天开始,并持续到第二天,直到找到工作日。这最多需要2个增量,因为最坏的情况是第2天是星期六,3星期日。我们的目标将是第4天。如果星期日是第二天,我们的目标是3,否则所需的日期是该月的第二天。我的first_wday
方法也会返回Date
个对象。您可以使用.day
来获取当月的某一天,或使用.wday
来获取星期几。
require 'date'
def first_wday(date)
d = Date.new(date.year, date.month, 2)
d += 1 while d.wday == 6 || d.wday == 0 # Saturday or Sunday
d
end
(1..12).each do |month|
date = Date.new(2014, month, 1)
wday = first_wday(date)
puts wday.strftime('%9B %Y: %-d (%A)')
end
# January 2014: 2 (Thursday)
# February 2014: 3 (Monday)
# March 2014: 3 (Monday)
# April 2014: 2 (Wednesday)
# May 2014: 2 (Friday)
# June 2014: 2 (Monday)
# July 2014: 2 (Wednesday)
# August 2014: 4 (Monday)
# September 2014: 2 (Tuesday)
# October 2014: 2 (Thursday)
# November 2014: 3 (Monday)
# December 2014: 2 (Tuesday)
答案 1 :(得分:1)
这是一种做法。
<强>代码强>
require 'date'
d = Date.today
d = (d-d.day+2).next_month
(d..d+2).find { |i| (1..5).cover?(i.wday) }.strftime("%m-%d-%Y %a")
<强>解释强>
d = Date.today #=> #<Date:2014-04-28((2456776j,0s,0n),+0s,2299161j)>
d = (d-d.day+2) #=> #<Date:2014-04-02((2456750j,0s,0n),+0s,2299161j)>
d = d.next_month #=> #<Date:2014-05-02((2456780j,0s,0n),+0s,2299161j)>
d.month #=> 5
d.year #=> 2014
d.wday #=> 5 (Friday)
该月的前三天中至少有一天是工作日,因此我们只需要考虑范围(d..d+2)
。传递给块的(d..d+2)
的第一个值是d
,所以:
i = d #=> #<Date: 2014-05-02 ((2456780j,0s,0n),+0s,2299161j)>
i.wday #=> 5
由于Date
周的周日从0开始,五周工作日为1..5
:
(1..5).cover?(i.wday) #=> true
(1..5).cover?(4) #=> true
所以
i.strftime("%m-%d-%Y %a") #=> "05-02-2014 Fri"
返回。