我正在创建一个程序,可以让用户更轻松地编写电子邮件,但是我需要找到一种方法来跳过周六和周日,在我们的待处理电子邮件过程中,用户是给予6天的回复,所以我需要的是让Ruby的Date
课程在星期六和星期日跳过并保持6天的准确计数,不包括周末。
例如:
require 'date'
date = Date.today
#=> #<Date: 2016-05-06 ((2457515j,0s,0n),+0s,2299161j)>
new_date = date + 6
#=> #<Date: 2016-05-12 ((2457521j,0s,0n),+0s,2299161j)>
new_date.strftime('%A')
#=> "Thursday"
date.strftime('%A')
#=> "Friday"
显然这个例子计算在周六和周日,所以我如何跳过这两天并保持计数准确?
答案 0 :(得分:4)
以下是您对Ruby要求的描述的直译:
require "date"
p today = Date.today
p (1..Float::INFINITY)
.lazy
.map { |offset| today + offset }
.reject { |date| date.saturday? || date.sunday? }
.drop(5)
.next
代码会创建从明天开始的所有日期的惰性枚举,拒绝所有星期六和星期日,删除接下来的5个有效候选人,然后返回下一个。
输出:
#<Date: 2016-05-06 ((2457515j,0s,0n),+0s,2299161j)>
#<Date: 2016-05-16 ((2457525j,0s,0n),+0s,2299161j)>
快速查看日历显示输出正确。
答案 1 :(得分:4)
您可以使用Date#saturday?
和Date#sunday?
或,您可以使用business time gem来为您处理所有这些问题。根据您的需要进行配置(例如,设置&#34;工作时间&#34;从午夜 - >午夜,如果这是您想要的),您可以做各种各样的事情,如:
6.business_days.after(Date.new(2014, 02, 7))
6.business_days.from_now
等等。
答案 2 :(得分:2)
>> require 'date'
=> true
>> d = Date.new(2016, 05, 3)
=> #<Date: 2016-05-03 ((2457512j,0s,0n),+0s,2299161j)>
>> d.saturday?
=> false
>> d.sunday?
=> false
>> a = d + 6
=> #<Date: 2016-05-09 ((2457518j,0s,0n),+0s,2299161j)>
>> a.saturday?
=> false
>> d = Date.today
=> #<Date: 2016-05-06 ((2457515j,0s,0n),+0s,2299161j)>
>> a = d + 1
=> #<Date: 2016-05-07 ((2457516j,0s,0n),+0s,2299161j)>
>> a.saturday?
=> true