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

后端 未结 5 1093
耶瑟儿~
耶瑟儿~ 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:36

    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.

提交回复
热议问题