什么是Ruby的弃用“Date.day_fraction_to_time”的现代等价物?

时间:2017-10-12 19:58:18

标签: ruby

  • ruby​​ 2.3.3p222(2016-11-21修订版56859)[x86_64-darwin16]

尝试运行this example(已修改为使用puts调试并使用即将到来的生日日期):

# http://www.techotopia.com/index.php/Working_with_Dates_and_Times_in_Ruby#Calculating_the_Difference_Between_Dates
require 'date'

today = DateTime.now
# => #<DateTime: 441799066630193/180000000,-301/1440,2299161>
puts "Today: " + today.to_s

# birthday = Date.new(2008, 4, 10)
birthday = Date.new(2017, 11, 8)
# => #<Date: 4909133/2,0,2299161>
puts "Birthday: " + birthday.to_s

# days_to_go = birthday - today
# puts days_to_go

time_until = birthday - today
# => Rational(22903369807, 180000000)
puts "Time Until: " + time_until.to_s

time_until.to_i             # get the number of days until my birthday
# => 127
puts "Time Until (integer): " + time_until.to_i.to_s

hours,minutes,seconds,frac = Date.day_fraction_to_time(time_until)
# [3053, 46, 57, Rational(1057, 180000000)]

puts "It is my birthday in #{hours} hours, #{minutes} minutes and #{seconds} seconds (not that I am counting)"
# It is my birthday in 3053 hours, 46 minutes and 57 seconds (not that I am counting)

但是当我尝试运行它时,它会在day_fration_to_time处中断,因为该方法为deprecated

$ ruby birthday.rb
Today: 2017-10-12T15:46:15-04:00
Birthday: 2017-11-08
Time Until: 150774970751/5760000000
Time Until (integer): 26
birthday.rb:24:in `<main>': undefined method `day_fraction_to_time' for Date:Class (NoMethodError)

我看到有另一个名为day_fraction的方法,但我不知道如何/如何使用它来获得与以前相同的结果。

2 个答案:

答案 0 :(得分:2)

您可以随时将其添加回项目:

class Date
  def self.day_fraction_to_time(fr)
    ss,  fr = fr.divmod(86_400) # 4p
    h,   ss = ss.divmod(3600)
    min, s  = ss.divmod(60)
    return h, min, s, fr
  end
end

答案 1 :(得分:0)

你可以这样做:

seconds = 1234
Time.at(seconds).utc.strftime("%H:%M")
=> "00:20"