Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse days/hours/minutes/seconds in ruby?

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?

like image 713
mannicken Avatar asked Mar 18 '09 08:03

mannicken


3 Answers

chronic_duration does this.

like image 149
srboisvert Avatar answered Nov 14 '22 14:11

srboisvert


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.

like image 31
August Lilleaas Avatar answered Nov 14 '22 13:11

August Lilleaas


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
like image 3
DanSingerman Avatar answered Nov 14 '22 14:11

DanSingerman