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?
Posting a 2nd answer, as chronic (which my original answer suggested) doesn't give you timespans but timestamps.
Here's my go on a parser.
class TimeParser
TOKENS = {
"m" => (60),
"h" => (60 * 60),
"d" => (60 * 60 * 24)
}
attr_reader :time
def initialize(input)
@input = input
@time = 0
parse
end
def parse
@input.scan(/(\d+)(\w)/).each do |amount, measure|
@time += amount.to_i * TOKENS[measure]
end
end
end
The strategy is fairly simple. Split "5h"
into ["5", "h"]
, define how many seconds "h"
represents (TOKENS
), and add that amount to @time
.
TimeParser.new("1m").time
# => 60
TimeParser.new("1m wtf lol").time
# => 60
TimeParser.new("4h 30m").time
# => 16200
TimeParser.new("1d 4h").time
# => 100800
It shouldn't be too hard making it handle "1.5h"
either, seeing the codebase is as simple as it is.