ironsand
ironsand

Reputation: 15151

How to get a last business day of a month with `business_time` gem

I want to get a last day of a month by using business_time gem.

This code works if the first day of the month is a business day.

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

But if the first day is not a business day, it returns a day earlier like this:

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

How can I get a last business day of a month by ruby? If necessary I'll use another gem.

Upvotes: 2

Views: 979

Answers (4)

Rodrigo Assis
Rodrigo Assis

Reputation: 121

This is how I did it with business_time gem:

Time.previous_business_day(Date.parse("2014-12-01") - 1.day)

Upvotes: 0

daino3
daino3

Reputation: 4566

Sort of a modified version of Sachin's response that uses the Holiday gem to take into consideration US holidays.

# 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

Upvotes: 0

Max
Max

Reputation: 22325

You don't need a gem, really

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'

Upvotes: 1

Sachin Singh
Sachin Singh

Reputation: 7225

try this out:

install the gem week_of_month

In IRB try:

   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)>

Upvotes: 2

Related Questions