From: "ara.t.howard" Date: 2008-09-28T15:26:18+09:00 Subject: Re: Parsing a time span On Sep 27, 2008, at 9:50 PM, Eric Marthinsen wrote: > 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 > -- > 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/ -- we can deny everything, except that we have the possibility of being better. simply reflect on that. h.h. the 14th dalai lama