start date = "2013-06-01"
end date = "2013-12-01"
我想要达到星期一和星期二在这个日期范围内发生多少次?
specific_days = 2 #monday and tuesday
total days = end_date - start_date
total_weeks = total_days/7
total_specific_days = total_weeks * specific_days
但这并不能确保星期一和星期二的出现
答案 0 :(得分:4)
使用Date类的wday method返回星期几(0-6,星期日为零),因此Mon为1,Tue为2。
require 'date'
dates = [*Date.new(2014,1,1)..Date.new(2014,10,1)]
p dates.count{|d| (d.wday == 1) || (d.wday == 2) }
结果:
#=> 78
<强>更新强>
比较array
和range
套:
require 'date'
require 'benchmark'
d1 = [*Date.new(2013,2,11)..Date.new(2013,12,25)]
d2 = Date.new(2013,2,11)..Date.new(2013,12,25)
n = 10000
Benchmark.bm do |x|
x.report('array') { n.times do d1.count{|d| (d.wday == 1) || (d.wday == 2) }; end }
x.report('range') { n.times do d2.count{|d| (d.wday == 1) || (d.wday == 2) }; end }
end
结果:
user system total real
array 0.405000 0.000000 0.405000 ( 0.419041)
range 1.498000 0.000000 1.498000 ( 1.505150)
答案 1 :(得分:3)
使用Date#monday?
,Date#tuesday?
和Enumerable#count
更加冗长:
require 'date'
start_date = Date.parse("2013-06-01")
end_date = Date.parse("2013-12-01")
(start_date..end_date).count { |d| d.monday? || d.tuesday? }
#=> 78
答案 2 :(得分:2)
此问题与How do I get all Sundays between two dates in Ruby?非常相似。
获取此日期之间的所有日期,并选择工作日编号为1
或2
的日期。星期日是第一个工作日(= 0
)。
require 'date'
start_date = DateTime.parse('2013-06-01')
end_date = DateTime.parse('2013-12-01')
result = (start_date..end_date).to_a.select { |d| [1,2].include?(d.wday) }
result.count
结果为52
次。
答案 3 :(得分:2)
=> (Date.parse(start_date)..Date.parse(end_date)).count{|d| d.wday == 1 || d.wday == 2 }
# 52