module Rufus
def self.parse_time_string(string)
or responds to #to_s will be OK.
Note will call #to_s on the input "string", so anything that is a String
Rufus.parse_time_string "1w2d" # => 777600.0
Rufus.parse_time_string "1h10s" # => 3610.0
Rufus.parse_time_string "1h" # => 3600.0
Rufus.parse_time_string "1000" # => 1.0
Rufus.parse_time_string "500" # => 0.5
Rufus.parse_time_string "0.5" # => 0.5
Some examples :
'nada' -> millisecond
y -> year
M -> month
s -> second
m -> minute
h -> hour
d -> day
w -> week
(millisecond count).
turns a time duration expressed as a string into a Float instance
Turns a string like '1m10s' into a float like '70.0', more formally,
def self.parse_time_string(string) string = string.to_s return 0.0 if string == '' m = string.match(/^(-?)([\d\.#{DURATION_LETTERS}]+)$/) raise ArgumentError.new("cannot parse '#{string}'") unless m mod = m[1] == '-' ? -1.0 : 1.0 val = 0.0 s = m[2] while s.length > 0 m = nil if m = s.match(/^(\d+|\d+\.\d*|\d*\.\d+)([#{DURATION_LETTERS}])(.*)$/) val += m[1].to_f * DURATIONS[m[2]] elsif s.match(/^\d+$/) val += s.to_i / 1000.0 elsif s.match(/^\d*\.\d*$/) val += s.to_f else raise ArgumentError.new("cannot parse '#{string}' (especially '#{s}')") end break unless m && m[3] s = m[3] end mod * val end