Ruby "hours" problem

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?

Thanks!

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.

I think GitHub - bokmann/business_time: Support for doing time math in business hours and days can handle this.

Great. That did the job!

I managed to do it using the GitHub - bokmann/business_time: Support for doing time math in business hours and days gem. Look for the business_time_until method.

1 Like