← Back to Upcase

Ruby "hours" problem

(Mark Joel Chavez) #1

Hey folks,

How do you get the working hours difference between two datetimes so that a datetime that is created today and a datetime of tomorrow will result in 8 hours not 24?


(Geoff Harcourt) #2

I would be very interested to see others’ approach to solve this problem, as it’s something that I have to deal with all the time.

At the current time, I solve this issue by creating a new Time object for one of the days (we’ll say today in this example), then using #change with a hash containing {hour: hour, min: min, sec: sec} to map the hours, minutes, and seconds over from tomorrow to this new time object.

Reminder to make sure you are handling time zones correctly! In the case you describe, since the day makes a big difference, I’d want to be sure that both objects that are getting compared are in the correct local time zone so that you don’t accidentally end up a day off if you cross midnight.

(Andy Waite) #3

I think https://github.com/bokmann/business_time can handle this.

(Mark Joel Chavez) #4

Great. That did the job!

(Mark Joel Chavez) #5

I managed to do it using the https://github.com/bokmann/business_time gem. Look for the business_time_until method.