Skip to content

Instantly share code, notes, and snippets.

@alhafoudh
Created October 9, 2009 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alhafoudh/1767d68f93e2873be64d to your computer and use it in GitHub Desktop.
Save alhafoudh/1767d68f93e2873be64d to your computer and use it in GitHub Desktop.
require "time"
# Author: Ahmed Al Hafoudh <alhafoudh@freevision.sk>
# Date: 2009-10-09
def average_time_of_day(times)
last = Time.at(0) # keep last time
cum = sum = 0 # cum -> day span cumulation
# sum -> unixtime summary
times.each do |t|
tt = Time.parse(t) # get the Time class instance from the string
cum += 86400 if tt < last # if the time we are just parsing is before the time we parsed last time increment the day span cumulation by one day
sum += (tt + cum).to_i # sum the unixtime seconds
last = tt # set the new last time
end
Time.at(sum / times.length).strftime("%I:%M%p").downcase # calculate average time and format the output
end
if __FILE__ == $0
# Some simple test cases
# Input values from the text
puts average_time_of_day(["11:15pm", "12:03am", "11:30pm", "11:23pm" ,"11:48pm"])
# Code example on the page
puts average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
puts average_time_of_day(["6:41am", "6:51am", "7:01am"])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment