Created
October 8, 2009 13:06
-
-
Save rhyhann/205002 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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