Skip to content
Create a gist now

Instantly share code, notes, and snippets.

@joshbax /joshbaxley.rb secret
Created Oct 16, 2009

require "parsedate"
include ParseDate
def average_time_of_day(times_array)
#Reduce the string array to an array of hours followed by seconds
times_array.collect! { |i| parsedate(i) }
#get length of new array
n = times_array.length
#get array indices of hours (even) and minutes (odd)
hours_indices = (0..n).find_all { |i| i%2 == 0 }
minutes_indices = (0..n).find_all { |i| i%2 == 1 }
#pick a starting point
epoch =
#set up empty array that will hold our times as numbers that we can average
t = []
#iterate through hours and minutes and make them universal time integers
(n/2).times do |i|
#now we need to make sure the times are sufficiently close to each other
#so we have a meaningful average. If the times differ by 12 hours, we need to
#adjust the AM times so they fall on the day following the PM times
if ( - > 12
t.collect! { |i|
if < 12
(i + 60*60*24)
#average our times
avg = (t.inject { |sum,k| sum+k }) / t.length
##test cases
#this should be 12:01pm
#puts average_time_of_day(["11:51am", "11:56am", "12:01pm", "12:06pm", "12:11pm"])
#this should be 12:01am
#puts average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
#this should be 6:51am
#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
Something went wrong with that request. Please try again.