I've got the follo开发者_开发技巧wing time string that I need to convert to a number of seconds since midnight (start of day). I've been looking in the Ruby Api but haven't been able to come up with a solution. Any ideas would be appreciated.
time_string = '4:12:38 PM ET'
To convert your string to a time use
new_time = Time.parse(time_string)
This will return a Time object. Then you can just subtract the time at midnight from your given time like so:
midnight = Time.local(2010,2,13,0,0,0)
seconds = (new_time - midnight).to_i # Number of seconds as an integer, .to_f works too
Of course, for Time.local, you should use today's date, not the hardcoded values as above.
If you have the active_support installed you can also do this
require 'rubygems'
require 'time'
require 'active_support/core_ext/time/calculations'
puts Time.parse('4:12:38 PM ET').seconds_since_midnight.to_i
精彩评论