Skip to content

Instantly share code, notes, and snippets.

@rhyhann
Created October 8, 2009 13:06
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 rhyhann/205002 to your computer and use it in GitHub Desktop.
Save rhyhann/205002 to your computer and use it in GitHub Desktop.
$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