【问题标题】:Number of hours between two dates - Ruby两个日期之间的小时数 - Ruby
【发布时间】:2015-06-28 08:47:13
【问题描述】:

假设我想要明天和现在之间的差异(以小时为单位)。

我尝试过的:

t = (DateTime.tomorrow - DateTime.now)
(t / 3600).to_i
=> 0

为什么是0?

我做错了什么?

【问题讨论】:

  • DateTime.tomorrow 和 DateTime.now 的值是多少?
  • Rails Time difference in hours 的可能重复项
  • 今天和明天有什么区别? 0,因为今天和明天之间没有时间? 24 小时,因为它们是不同的日子,一天有 24 小时?

标签: ruby-on-rails ruby


【解决方案1】:

这是因为DateTime.tomorrow 没有任何时间价值。这里:

DateTime.tomorrow
# => Wed, 22 Apr 2015

如果你通过official document for DateTime你可以看到没有方法tomorrow。它基本上是Date#tomorrow

您可以使用.to_time 获取默认本地时间00:00:00

DateTime.tomorrow.to_time
# => 2015-04-22 00:00:00 +0530

(DateTime.tomorrow.to_time - DateTime.now) / 1.hours
# => 9.008116581638655

要获得日期之间的精确小时差:

(DateTime.tomorrow.to_time - Date.today.to_time) / 1.hours 
# => 24.0

【讨论】:

  • 你也可以使用 (1.day.from_now - DateTime.now) / 3600
【解决方案2】:

它返回有理数。如果您使用round 方法,则可以取天数:

>> (DateTime.tomorrow - DateTime.now).round
1

或者,如果您想在数小时后获得价值,请使用 Time 类:

>> (Date.tomorrow.to_time - Time.now) / 1.hour
11.119436663611111

【讨论】:

    【解决方案3】:

    试试这个

    t = (DateTime.tomorrow.to_time - Date.today.to_time)
    t = (t / 3600).to_i
    

    【讨论】:

      【解决方案4】:

      如果你有两个日期,比如

      start_time = Time.new(2015,1, 22, 35, 0)
      end_time = Time.new(2015,2, 22, 55, 0)
      

      https://rubygems.org/gems/time_difference 试用 Ruby 的 Time Difference gem

      def timediff(start, end)
        TimeDifference.between(start, end).in_hours
      end
      

      然后这样称呼它:

      timediff(start_time, end_time)
      

      它会起作用的。 干杯!

      【讨论】:

      • 你真的不需要 gem 来完成这么简单的任务,如果它可以用一行代码编写,那么你只需将膨胀添加到你的应用程序 IMO。
      • 我同意你的看法@David Battersby。我只是说这个答案,这也是一种处理方式。
      【解决方案5】:

      DateTime#seconds_until_end_of_day:

      seconds = DateTime.now.seconds_until_end_of_day
      #=> 41133
      
      seconds / 3600
      #=> 11
      
      distance_of_time_in_words(seconds)
      => "about 11 hours"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多