current_time = Time.new
due_time = # … some Time instance in the future
work_hours_left_before_I_am_screwed = # … calculate
I’m writing a little task-tracking app to help me put out the most
urgent fires. As above, given any two Time instances, I’d like to know
how many hours are left to perform the task. This should skip weekends
and hours outside of specified start- and end-hours for a work day.
Anyone got such code handy? Or feel like writing it for me?
Right now, my best idea involves looping over the range one day at a
time and manually accumulating the available hours. It feels
inelegant, but it’s all I have right now.
current_time = Time.new
due_time = # … some Time instance in the future
work_hours_left_before_I_am_screwed = # … calculate
I’m writing a little task-tracking app to help me put out the most
urgent fires. As above, given any two Time instances, I’d like to know
how many hours are left to perform the task. This should skip weekends
and hours outside of specified start- and end-hours for a work day.
Anyone got such code handy? Or feel like writing it for me?
Hmm… no idea if this works, but it might be a start:
#!/usr/bin/env ruby
class WorkHours
SECONDS_IN_HOUR = 3600
HOURS_I_WORK = (7…16)
DAYS_I_WORK = (1…5)
def self.diff_times(a, b)
hours = []
(a.to_i…b.to_i).step(SECONDS_IN_HOUR) {|t|
time = Time.at(t)
hours << t if DAYS_I_WORK.include?(time.wday) &&
HOURS_I_WORK.include?(time.hour)
}
return hours.length
end
end
nil
if start_time.yday == end_time.yday
if weekdays.include?( start_time.wday )
( end_time - start_time ) / one_hour
else
0
end
else
business_hours = work_ends_at - work_starts_at
# Handle partial hours on the first day
hours = ( start_time.at( work_ends_at ) - start_time ) / one_hour
t = start_time + one_day
until t.yday == due_time.yday
hours += business_hours if weekdays.include?( t.wday )
t += one_day
end
# Handle partial hours on the last day
if weekdays.include?( t.wday )
hours += ( end_time - end_time.at( work_starts_at ) ) / one_hour
end
hours
end
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.