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

后端 未结 5 1117
耶瑟儿~
耶瑟儿~ 2021-02-13 20:55

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?

5条回答
  •  故里飘歌
    2021-02-13 21:44

    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
    

提交回复
热议问题