Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
$am_pm = false
def average_time_of_day(times)
Time.at(
times.map! { |t| if t =~ /(\d+):(\d+)(\w*)/
military = ($1+$2).to_i
[if (1200..1259) === military && $3 == 'am'; 0
elsif (100..1159) === military && $3 == 'pm'; $1.to_i+12
else; $1.to_i
end, $2.to_i]
end}.map!.with_index {|t,i| t[0] += 24 if t[0] < times[i-1][0] && i!=0; t}.
inject(0) {|sum,a| sum + a[0]*3600 + a[1]*60}/times.size
).strftime($am_pm ? "%I:%M%p" : "%H:%M").downcase
end
# To avoid confusion, a 24-hour clock is used (I don't live in a country
# where am/pm is used, nor in a continent, nor near a continent)
# Still, I used this: http://www.mathsisfun.com/time.html to guide me
# through the conversion. Just change the first constant to true to get an am/pm
# result
# My trick here is to use Time.at not to be bored by reverse parsing, since
# it simply generates the time related to the seconds given since Epoch
# (1/1/70 00:00).
# I have chosen to code like if all the times were after the previous one.
# See line #11 for more informations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment