开发者

How to convert a time string to number of seconds in Ruby

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜