Question

I'm trying to take a string "00:04:55", and parse it into some sort of Ruby object so that I can get the total seconds. Something like in C# with a simple timespan.

Était-ce utile?

La solution

Using Time.strptime will do what you want (I think):

> require 'time' # not needed inside rails
> time = Time.strptime("06:04:55", "%H:%M:%S")
> time.sec
55
> time.min
4
> time.hour
6
> require 'active_support/core_ext' # not needed in rails
> time.seconds_since_midnight.to_i
21895

Autres conseils

You can use a trick, it is not very elegant but it should do:

Date.parse(Time.now.strftime("%d")+' '+"00:04:55")
# => #<Date: 2013-10-26 ((2456592j,0s,0n),+0s,2299161j)>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top