Is there a gem or something to parse strings like "4h 30m" "1d 4h" -- sort of like the estimates in JIRA or task planners, maybe, with internationalization?
chronic_duration
does this.
You can use chronic. It can parse pretty much everything you trhow at it, including "yesterday", "last week" etc.
Update: As the OP points out in the comment, Chronic is for dates, not timespans. See my other answer.
I wrote this method that does it pretty well
def parse_duration(dur)
duration = 0
number_tokens = dur.gsub(/[a-z]/i,"").split
times = dur.gsub(/[\.0-9]/,"").split
if number_tokens.size != times.size
raise "unrecognised duration!"
else
dur_tokens = number_tokens.zip(times)
for d in dur_tokens
number_part = d[0].to_f
time_part = d[1]
case time_part.downcase
when "h","hour","hours"
duration += number_part.hours
when "m","minute","minutes","min","mins"
duration += number_part.minutes
when "d","day","days"
duration += number_part.days
when "w","week","weeks"
duration += number_part.weeks
when "month", "months"
duration += number_part.months
when "y", "year", "years"
duration += number_part.years
else
raise "unrecognised duration!"
end
end
end
duration
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With