Parsing a time span

Hello-

I’m trying to find the best way to turn a string like “3 days” or “72
hours” into some sort of time span representation. My first question is
what is the best way to store a duration like this? In seconds? Second,
are there any good tools for parsing a string like this? I’m aware of
the Duration library, but the author doesn’t consider it stable, so I’d
prefer something stable and supported. Thanks in advance.

Regards-
Eric

Oh, and it looks like Duration doesn’t parse the way I want to, so any
other ideas would be much appreciated.

-Eric

On Sun, Sep 28, 2008 at 1:08 PM, Eric M.
[email protected] wrote:

Oh, and it looks like Duration doesn’t parse the way I want to, so any
other ideas would be much appreciated.

Hi,

I have something like that available from the “rufus-scheduler” gem :

http://rufus.rubyforge.org/rufus-scheduler/classes/Rufus.html#M000006

—8<—
require ‘rubygems’
require ‘rufus/scheduler’
Rufus.parse_time_string “500” # => 0.5
Rufus.parse_time_string “1000” # => 1.0
Rufus.parse_time_string “1h” # => 3600.0
Rufus.parse_time_string “1h10s” # => 3610.0
Rufus.parse_time_string “1w2d” # => 777600.0
—>8—

Best regards,

Thanks. I’ll check it out.

On Sep 27, 2008, at 9:50 PM, Eric M. wrote:

prefer something stable and supported. Thanks in advance.

Regards-
Eric

Posted via http://www.ruby-forum.com/.

very liberal, but useful

cfp:~ > cat a.rb
def duration_for spec
ret = nil
if((m = %r/^ (\d+(?:.\d+)?) : (\d+(?:.\d+)?) : (\d+(?:.\d+)?) $/
iox.match(spec.to_s)))
m, h, m, s, ignored = m.to_a
h, m, s = Float(h), Float(m), Float(s)
ret = (h * 60 * 60) + (m * 60) + (s)
else
pat = %r/(\d+(?:.\d+)?)\s*([sSmMhHdDwWyY][^\d]*)?/
begin
“#{ spec }”.scan(pat) do |m|
n = Float m[0]
unit = m[1]
if unit
factor =
case unit
when %r/^m/i
case unit
when %r/^mo/i
7 * (60 * 60 * 24)
else
60
end
when %r/^h/i
60 * 60
when %r/^d/i
60 * 60 * 24
when %r/^w/i
7 * (60 * 60 * 24)
when %r/^y/i
365 * 7 * (60 * 60 * 24)
else
1
end
n *= factor
end
ret ||= 0.0
ret += n
end
rescue
raise “bad time spec <#{ spec }>”
end
end
ret
end

p duration_for(‘1 minute’)
p duration_for(‘1 hour and 1 minute’)
p duration_for(‘6 days, 3 hours and 1 minute’)

cfp:~ > ruby a.rb
60.0
3660.0
529260.0

a @ http://codeforpeople.com/