如何在ruby中解析天/小时/分钟/秒?

时间:2009-03-18 08:03:21

标签: ruby parsing time rubygems

是否有一个宝石或其他东西来解析像“4h 30m”“1d 4h”这样的字符串 - 有点像JIRA或任务规划人员的估计,也许是国际化?

5 个答案:

答案 0 :(得分:12)

发布第二个答案,因为慢性(我的原始答案建议)不会给你时间戳而是时间戳。

这是我的解析器。

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

策略相当简单。将"5h"拆分为["5", "h"],定义"h"代表的秒数(TOKENS),并将该金额添加到@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

让它处理"1.5h"也不会太难,因为看到代码库就像它一样简单。

答案 1 :(得分:9)

chronic_duration这样做。

答案 2 :(得分:6)

您可以使用chronic。它几乎可以解析你所做的一切,包括“昨天”,“上周”等等。

更新:正如OP在评论中指出的那样,Chronic是针对日期而不是时间跨度。看到我的其他答案。

答案 3 :(得分:3)

我写的这个方法很好用

  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

答案 4 :(得分:1)

虽然解析了什么?

这将解析为Hash:

"4h 30m".split(/\s/).each{|i| h[i.gsub(/\d+/,"")] = i.gsub(/\w/,"")}

对不起。不熟悉JIRA ......