Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
require "time"
# Author: Ahmed Al Hafoudh <>
# Date: 2009-10-09
def average_time_of_day(times)
last = # 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 / times.length).strftime("%I:%M%p").downcase # calculate average time and format the output
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"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment