2014-10-17 63 views
2

我想通過使用business_time寶石來得到一個月的最後一天。如何通過`business_time`獲得一個月的最後一個工作日寶石

如果每個月的第一天是營業日,此代碼將起作用。

1.business_day.before(Date.parse("2014-12-01")) 

但是,如果第一天是不是工作日,則返回前面這樣的日子:

1.business_day.before(Date.parse("2014-11-01")) # => 2014-10-30 (It should be 2014-10-31) 

我怎麼可以由紅寶石獲得一個月的最後一個營業日? 如有需要,我會使用另一顆寶石。

回答

1

你並不需要一個寶石,真的

require 'time' 

def last_business_day date 
    day = Date.parse(date).next_month 
    loop do 
    day = day.prev_day 
    break unless day.saturday? or day.sunday? 
    end 
    day 
end 

last_business_day '2014-11-01' # => '2014-11-28' 
last_business_day '2014-12-01' # => '2014-12-31' 
2

嘗試了這一點:

安裝寶石week_of_month

在IRB嘗試:

require 'week_of_month' 

    date = Date.parse("2014-11-01") 

    date.end_of_month.downto(date).find{|day| day.working_day? } 
    => #<Date: 2014-11-28 ((2456990j,0s,0n),+0s,2299161j)> 
+0

沒有'week_of_month',只需更換''day.working_day通過'day.wday.in? 1..5' – Habax 2016-05-17 13:51:11

0

排序的Sachin的修改版本使用Holiday Gem來考慮U. S假期。

# lib/holidays/business_day_helpers.rb 
require 'holidays' 

module Holidays 
    module BusinessDayHelpers 
    def business_day?(calendar = :federal_reserve) 
     !holiday?(calendar) && !saturday? && !sunday? 
    end 

    def last_business_day_of_the_month(calendar = :federal_reserve) 
     end_of_month.downto(beginning_of_month).find(&:business_day?) 
    end 

    def last_business_day_of_the_week(calendar = :federal_reserve) 
     end_of_week.downto(beginning_of_week).find(&:business_day?) 
    end 
    end 
end 

Date.include Holidays::BusinessDayHelpers 
0

這是我做到了與business_time寶石:

Time.previous_business_day(Date.parse("2014-12-01") - 1.day) 
相關問題