2014-10-17 125 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) 
相关问题