在 Rails 4 中尝试将持续时间转换为毫秒时得到 "argument out of range"

Getting "argument out of range" when trying to turn a duration into milliseconds in Rails 4

我正在使用 Rails 4.2.4。我有以下将时间(持续时间)转换为毫秒的方法……

Time.parse(convert_to_hrs(duration)).seconds_since_midnight * 1000

其中方法“convert_to_hrs”定义为

    def convert_to_hrs(string)
      case string.count(':')
      when 0
        '00:00:' + string.rjust(2, '0')
      when 1
        '00:' + string
      else
        string
      end
    end

但是,如果持续时间非常长(例如“34:13:00”——读作:34 小时 13 分钟 0 秒),上述操作会失败并出现错误

Error during processing: argument out of range
/Users/mikea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/time.rb:302:in `local'
/Users/mikea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/time.rb:302:in `make_time'
/Users/mikea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/time.rb:366:in `parse'
/Users/mikea/Documents/workspace/myproject/app/services/my_service.rb:25:in `block in process_page_data'
/Users/mikea/Documents/workspace/myproject/app/services/my_service.rb:22:in `each'
/Users/mikea/Documents/workspace/myproject/app/services/my_service.rb:22:in `process_page_data'

如何重写我的第一行以准确地将持续时间转换为毫秒?

Time.parse 抛出错误,因为您传入 duration 变量的值超出范围。

例如: Time.parse(convert_to_hrs('59:59')) 根据你写的 code,它是 return 2016-07-27 00:59:59 +0530

这里的值59:59被认为是minutes:seconds,所以如果你传递值60:60那么它会引发错误argument out of range

HereTime

parse方法的官方文档

希望对您有所帮助。

如果您知道自己将始终使用 hours:minutes:seconds 格式,但不保证每个字段中的数字都在 'normal' 范围内(例如 0-23小时,0-59 分钟,等等),那么你可能最好 'manually' 使用这样的东西:

def duration_in_milliseconds(input)
  h, m, s = input.split(':').map(&:to_i)
  (h.hours + m.minutes + s.seconds) * 1000
end

puts duration_in_milliseconds('34:13:00') #=> 123180000

请注意,这仅适用于 ActiveSupport,但您拥有它,因为您指定了 Rails。此外,这假设您总是获得所有三个术语(例如 5 秒是 00:00:05)。接受较短字符串的完整设置也希望使用您的 convert_to_hrs 方法。

另请注意,即使格式不严格 'time-like',只要您使用一致的冒号作为分隔符,这也有效:

puts duration_in_milliseconds('1:1:5') #=> 3665000

Numeric#hours, Numeric#minutes and Numeric#seconds methods are provided by ActiveSupport, as part of active_support/core-ext/time.rb. They aren't particularly documented, but they return ActiveSupport::Duration 对象,它们具有与 5.days.ago 等时间和日期问题交互的奇特方法,但当被视为整数时,实际上是几秒。