sumikko engineer blog

すみっこが落ち着くエンジニアのブログです。

rubyで営業日を取得する

メンテナンスされるかわからないgemを使いたくなかったので簡単に自作しました。 祝日、年末やその他の休みを好き勝手に入れたい場合はpublic_holidaysをメンテをしていく。

月~金までが営業日 祝日、年末は休み

require 'singleton'
require 'date'

class BusinessDate
  include Singleton
  @@public_holidays = [
    "2021-11-3",
    "2021-11-23",
    "2021-12-30",
    "2021-12-31",
    "2022-1-1",
    "2022-1-2",
    "2022-1-3",
    "2022-1-4"
  ]

  def initialize
    @today = Date.today
  end

  def public_holiday?(_date)
    @@public_holidays.include?("#{_date.year}-#{_date.month}-#{_date.day}")
  end

  def holiday?(_date)
    _date.sunday? || _date.saturday?
  end

  def business_date?(_date)
    !holiday?(_date) && !public_holiday?(_date)
  end

  def business_beginning_of_month?(_date)
    target_business_date = _date.beginning_of_month
    if target_business_date == _date
      return true if business_date?(_date)
      return false
    end

    while !business_date?(target_business_date)
      target_business_date = target_business_date + 1
    end

    return true if target_business_date == _date
    false
  end

  def prev_business_date(_date)
    target_date = _date
    if business_date?(target_date)
      if target_date.monday?
        # 月曜日の場合は金曜日を取得する
        target_date = target_date - 3
      else
        target_date = target_date - 1
      end
    end

    while !business_date?(target_date)
      target_date = target_date - 1
    end
    target_date
  end

end
メソッド名 内容
public_holiday? 祝日か判定する。@@public_holidaysのメンテが必要
holiday? 休日か判定する。土日休み
business_date? 営業日か判定する。祝日、土日以外は営業日
business_beginning_of_month? 営業月初か判定する。月初が土日、祝日なら遡って営業月初を取得する
prev_business_date 前日の営業日を取得する。月曜日の場合は金曜日。金曜日が祝日なら遡って営業日を取得する