Skip to content

Instantly share code, notes, and snippets.

@brycesenz
Last active August 29, 2015 13:56
Show Gist options
  • Save brycesenz/9237366 to your computer and use it in GitHub Desktop.
Save brycesenz/9237366 to your computer and use it in GitHub Desktop.
Solving TimeLogger problem for chat user.

I have a time range, ex: ["02:15", "04:30"] which shows a session begin and end time.

I need to break that down by the hour. End result would be: 2: 2700 3: 3600 4: 1800

The way I thought about doing this was breaking this down into the following array: ["02:15", "03:00", "04:00", "04:15"] and getting the time difference between the elements.. ie difference between 03:00 and 02:15 which results in 2700s, etc.

Any suggestions on something better? more efficient?

# For an array ["02:15", "04:30"]
TimeLogger.new("2:15", "4:30").hourly_breakdown # => {"2" => "2700", "3" => "3600", "4" => "1800}
require 'time'
class TimeLogger
def initialize(start_time, end_time)
@start_time = Time.parse(start_time)
@end_time = Time.parse(end_time)
end
def hourly_breakdown
output = {}
start_hour.upto(final_hour) do |hr|
output[hr.to_s] = minutes_of_hour(hr)
end
output
end
private
def start_hour
@start_time.hour
end
def final_hour
@end_time.hour
end
def minutes_of_hour(hr)
if (hr == start_hour)
(60 - @start_time.min) * 60
elsif (hr == final_hour)
(60 - @end_time.min) * 60
else
3600
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment