Skip to content

Instantly share code, notes, and snippets.

@craigp
Created August 2, 2010 15:20
Show Gist options
  • Save craigp/504802 to your computer and use it in GitHub Desktop.
Save craigp/504802 to your computer and use it in GitHub Desktop.
duration_for
#!/usr/bin/env ruby
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')
p duration_for('1 month, 6 days, 3 hours and 2 minutes')
@craigp
Copy link
Author

craigp commented Aug 2, 2010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment