Ruby 查找除周末外的日期
Ruby find date with your day except weekend
我想在您输入日期时生成一个 def get 日期。除了周末,我们每周工作 5 天。
例如:今天:27/02/2018
你输入:3 -> 输出:02/03/2018
你输入:5 -> 输出:06/03/2018
你输入:7 -> 输出:08/03/2018
你输入:10 -> 输出:13/03/2018
我的代码:
require 'date'
def next_week d, c
return d + 7 * c
end
def my_add_day day
d = Date.today
d = next_week d, day/5
day = day % 5
if (6 - d.wday) > day
d = d + day
else
d = d + day + 2
end
return d
end
你可以使用 gem https://github.com/bokmann/business_time
def add_working_days date, num
num.times.inject(date) do |date|
case date.wday
when 5 then date + 3
when 6 then date + 2
else date + 1
end
end
end
main ▶ add_working_days Date.today, 3
#⇒ #<Date: 2018-03-02 ((2458180j,0s,0n),+0s,2299161j)>
main ▶ add_working_days Date.today, 5
#⇒ #<Date: 2018-03-06 ((2458184j,0s,0n),+0s,2299161j)>
main ▶ add_working_days Date.today, 7
#⇒ #<Date: 2018-03-08 ((2458186j,0s,0n),+0s,2299161j)>
main ▶ add_working_days Date.today, 10
#⇒ #<Date: 2018-03-13 ((2458191j,0s,0n),+0s,2299161j)>
使用 business_time
gem(它允许额外的功能,例如定义 BusinessTime::Config.holidays
),这可以写成:
1.business_day.after(date)
或者作为更通用的辅助方法:
def add_working_days(date, num)
num.business_days.after(date)
end
如果这是一个需要在您的应用程序中解决的 common/complex 问题,我建议您使用这个库。
您可以使用 ruby 中的 lazy enumerator 跳过所有未来的周六和周日,并以无条件的函数式方式获取下一个工作日的日期。
def next_workday(number_of_days)
(DateTime.now..DateTime::Infinity.new)
.lazy
.reject { |x| x.saturday? || x.sunday? }
.drop(number_of_days)
.first
end
我想在您输入日期时生成一个 def get 日期。除了周末,我们每周工作 5 天。
例如:今天:27/02/2018
你输入:3 -> 输出:02/03/2018
你输入:5 -> 输出:06/03/2018
你输入:7 -> 输出:08/03/2018
你输入:10 -> 输出:13/03/2018
我的代码:
require 'date'
def next_week d, c
return d + 7 * c
end
def my_add_day day
d = Date.today
d = next_week d, day/5
day = day % 5
if (6 - d.wday) > day
d = d + day
else
d = d + day + 2
end
return d
end
你可以使用 gem https://github.com/bokmann/business_time
def add_working_days date, num
num.times.inject(date) do |date|
case date.wday
when 5 then date + 3
when 6 then date + 2
else date + 1
end
end
end
main ▶ add_working_days Date.today, 3
#⇒ #<Date: 2018-03-02 ((2458180j,0s,0n),+0s,2299161j)>
main ▶ add_working_days Date.today, 5
#⇒ #<Date: 2018-03-06 ((2458184j,0s,0n),+0s,2299161j)>
main ▶ add_working_days Date.today, 7
#⇒ #<Date: 2018-03-08 ((2458186j,0s,0n),+0s,2299161j)>
main ▶ add_working_days Date.today, 10
#⇒ #<Date: 2018-03-13 ((2458191j,0s,0n),+0s,2299161j)>
使用 business_time
gem(它允许额外的功能,例如定义 BusinessTime::Config.holidays
),这可以写成:
1.business_day.after(date)
或者作为更通用的辅助方法:
def add_working_days(date, num)
num.business_days.after(date)
end
如果这是一个需要在您的应用程序中解决的 common/complex 问题,我建议您使用这个库。
您可以使用 ruby 中的 lazy enumerator 跳过所有未来的周六和周日,并以无条件的函数式方式获取下一个工作日的日期。
def next_workday(number_of_days)
(DateTime.now..DateTime::Infinity.new)
.lazy
.reject { |x| x.saturday? || x.sunday? }
.drop(number_of_days)
.first
end