Module: BusinessTime::TimeExtensions

Included in:
ActiveSupport::TimeWithZone, Time
Defined in:
lib/business_time/time_extensions.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
# File 'lib/business_time/time_extensions.rb', line 3

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#business_time_until(to_time) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/business_time/time_extensions.rb', line 115

def business_time_until(to_time)
  # Make sure that we will calculate time from A to B "clockwise"
  if self < to_time
    time_a = self
    time_b = to_time
    direction = 1
  else
    time_a = to_time
    time_b = self
    direction = -1
  end

  # Align both times to the closest business hours
  time_a = Time::roll_forward(time_a)
  time_b = Time::roll_forward(time_b)

  if time_a.to_date == time_b.to_date
    time_b - time_a
  else
    end_of_workday = Time.end_of_workday(time_a)
    end_of_workday += 1 if end_of_workday.to_s =~ /23:59:59/

    first_day       = end_of_workday - time_a
    days_in_between = ((time_a.to_date + 1)..(time_b.to_date - 1)).sum{ |day| Time::work_hours_total(day) }
    last_day        = time_b - Time.beginning_of_workday(time_b)

    first_day + days_in_between + last_day
  end * direction
end