Ramiz Raja
Ramiz Raja

Reputation: 6030

Calculate service hours between two DateTime objects

How can I calculate number of hours/minutes between two DateTime objects, excluding off service hours.

For example I want to calculate number of service hours between 2017-09-13 17:50 and 2017-09-15 10:30, while service hours are 09:00 to 18:00 daily.

I would love to find some efficient solution for this.

Upvotes: 0

Views: 177

Answers (1)

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

You might be interested on this working_hours gem

require 'working_hours'

WorkingHours::Config.with_config(
  working_hours: {
    mon: {'09:00' => '18:00'},
    tue: {'09:00' => '18:00'},
    wed: {'09:00' => '18:00'},
    thu: {'09:00' => '18:00'},
    fri: {'09:00' => '18:00'},
    sat: {'09:00' => '18:00'},
    sun: {'09:00' => '18:00'},
  }
) do
  from = Time.parse('2017-09-13 17:50')
  to = Time.parse('2017-09-15 10:30')

  # in "seconds"
  service_hours = from.working_time_until(to)
end

Upvotes: 1

Related Questions