Help us understand the problem. What is going on with this article?

【Rails】business_time gemの祝日の設定方法と営業日計算

はじめに

Railsで営業日計算をするのに便利なgem business_timeの祝日の設定方法と営業日計算の紹介です。

祝日を設定する

祝日は以下のようにBusinessTime::Config.holidaysにセットしていきます。

holiday = Date.parse('2019/9/16') # 敬老の日
BusinessTime::Config.holidays << holiday
holiday = Date.parse('2019/9/23') # 秋分の日
BusinessTime::Config.holidays << holiday

注意したいのはDate型を入れないと祝日を含めて営業日計算できません。
ActiveSupport::TimeWithZone型ではダメです(特にエラーは出ないようなので注意!)。もし、ActiveSupport::TimeWithZone型ならば、以下のようにDate型に変換してあげればOKです。

holiday = Time.zone.local(2019, 9, 23) # 秋分の日
BusinessTime::Config.holidays << holiday.to_date

N営業日後を計算する

以下は10営業日後を計算する例です。なお、営業時間は24時間、営業日は月曜から金曜に設定にしています。

BusinessTime::Config.beginning_of_workday = "00:00:00"
BusinessTime::Config.end_of_workday       = "23:59:59"
BusinessTime::Config.work_week            = [:mon, :tue, :wed, :thu, :fri]
holiday = Date.parse('2019/9/16') # 敬老の日
BusinessTime::Config.holidays << holiday
holiday = Date.parse('2019/9/23') # 秋分の日
BusinessTime::Config.holidays << holiday

date = Time.zone.local(2019, 9, 7) # 土曜日
10.business_days.after(date)
=> Wed, 25 Sep 2019 09:00:00 JST +09:00

土曜日(9/7 Sat.)のように営業時間外を指定すると、翌営業日(9/9 Mon.)を起点に、その次の営業日(9/10 Tue.)を1営業日目として計算します。よって上記の例では、敬老の日と秋分の日が間にあるため、9/25が10営業日目となります。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした