Created
August 2, 2010 15:20
-
-
Save craigp/504802 to your computer and use it in GitHub Desktop.
duration_for
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found this here: http://www.ruby-forum.com/topic/166915