加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby,从Date.day_fraction_to_time获取小时,秒和时间

发布时间:2020-12-16 19:05:16 所属栏目:百科 来源:网络整理
导读:我发现这个方法 here. start = DateTime.now sleep 15 stop = DateTime.now #minutes puts ((stop-start) * 24 * 60).to_i hours,minutes,seconds,frac = Date.day_fraction_to_time(stop-start) 我有以下错误: `main': private method `day_fraction_to_ti
我发现这个方法 here.
start = DateTime.now
  sleep 15
  stop = DateTime.now
  #minutes
  puts ((stop-start) * 24 * 60).to_i

  hours,minutes,seconds,frac = Date.day_fraction_to_time(stop-start)

我有以下错误:

`<main>': private method `day_fraction_to_time' called for Date:Class (NoMethodError)

我检查了/usr/lib/ruby/1.9.1/date.rb,我发现了它:

def day_fraction_to_time(fr) # :nodoc:
  ss,fr = fr.divmod(SECONDS_IN_DAY) # 4p
  h,ss = ss.divmod(3600)
  min,s  = ss.divmod(60)
  return h,min,s,fr * 86400
end

但如果我用ruby1.8运行它,我没有问题. /usr/lib/ruby/1.8/date.rb给了我:

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

所以我去看了documentation(1.9),并没有这种方法的痕迹.我知道这是一个愚蠢的问题,但为什么他们删除它?甚至有关于如何在/usr/lib/ruby/1.9.1/date.rb中使用该方法的示例:

def secs_to_new_year(now = DateTime::now())
     new_year = DateTime.new(now.year + 1,1,1)
     dif = new_year - now
     hours,mins,secs,ignore_fractions = Date::day_fraction_to_time(dif)
     return hours * 60 * 60 + mins * 60 + secs
 end

但我仍然得到错误:

test.rb:24:in `secs_to_new_year': private method `day_fraction_to_time' called for Date:Class (NoMethodError)
    from test.rb:28:in `<main>'

解决方法

我不知道为什么它是私有的,但你仍然可以访问它:
hours,frac = Date.send(:day_fraction_to_time,stop-start)

这样你就可以覆盖OOP封装机制……这不是一件好事,但它确实有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读