Parsing a time span

E

Eric Marthinsen

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
 
E

Eric Marthinsen

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

-Eric
 
J

John Mettraux

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://github.com/jmettraux/rufus-scheduler
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,
 
A

ara.t.howard

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

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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,647
Latest member
NelleMacy9

Latest Threads

Top