【Rails】営業日を考量して日付を操るGem business_time
回答期限に応じて何かを処理するって時に営業日を考慮したい時があり色々調べているとスンバラシイですね。
business_time
っていうgemがあったので簡単な使い方を紹介します!
導入方法
Gemfile
を設定してbundle install
します。
# Gemfile gem 'business_time'
使い方
bundle exec rails c
で色々検証してみました。
日付の操作
現在日付
Time.current.to_s => "2019-07-09 21:48:18 +0900"
1日後
1.business_day.from_now.to_s => "2019-07-10 21:48:23 +0900"
1日前
1.business_day.ago.to_s => "2019-07-08 21:55:19 +0900"
1時間前
1.business_hour.ago.to_s => "2019-07-09 20:54:58 +0900"
営業日チェック
今日が営業日か
Date.today.to_s => "2019-07-09"
Date.today.workday? => true
7/9が営業日か
Date.parse("2019-07-09").workday? => true
7/13(土)が営業日か
Date.parse("2019-07-13").workday? => false
自分の誕生日が休日か?
my_birthday = Date.new(2019, 8, 4) => Sun, 04 Aug 2019
my_birthday.to_s => "2019-08-04"
my_birthday.workday? => false
注意点
Timezoneはきちんと設定しましょう!
TimeZoneはきちんとtokyoにしておかないと計算がおかしくなるので、注意です!
# confing/application.rb class Application < Rails::Application config.time_zone = 'Asia/Tokyo' end
きちんと設定されていれば、今の日付が表示されると思います。
Time.current.to_s => "2019-07-09 21:54:34 +0900"
1.business_hour.from_now.to_s => "2019-07-10 10:53:59 +0900"
が、この設定がないとおかしくなります。
Time.current.to_s => "2019-07-09 13:08:15 UTC"
1.business_hour.from_now.to_s => "2019-07-09 14:08:19 UTC"
営業時間の判定もされる
普通にやってると2日後とかになってあれっなると思います。
Time.current.to_s => "2019-07-09 22:09:30 +0900"
1.business_hour.from_now.to_s => "2019-07-10 11:00:00 +0900"
この場合は、1時間後が表示されるはずです。つまり2019-07-09 23:09:30 +0900
ですね。
が、このgemは営業時間を持っているのでその時間も考慮して計算しているので気をつけましょう。
こちらの設定については、こちらのコマンドを実行することでymlが作られそこに定義されています。
$ rails generate business_time:config
business_time: beginning_of_workday: 10:00 am end_of_workday: 10:00 pm holidays: - Jan 01, 2010 - July 4th, 2010 - December 25th, 2010 work_week: - mon - tue - wed - thu - fri
- beginning_of_workday: 開始時間
- end_of_workday: 終了時間