【问题标题】:How ActiveSupport TimeWithZone retains values?ActiveSupport TimeWithZone 如何保持价值?
【发布时间】:2019-06-30 16:23:53
【问题描述】:

我尝试过类似的方法:

a = ActiveSupport::TimeWithZone.new(Time.now,Time.zone)
b = a
a - b  # it gives 0.0 (float)

当我尝试时:

a.to_s  # it gives "2019-06-30 11:11:42 -0700"
a.to_a  # it gives [42, 11, 11, 30, 6, 2019, 0, 181, true, "PDT"]

那么这个浮点数是从哪里来的?

【问题讨论】:

    标签: ruby-on-rails activesupport


    【解决方案1】:

    Time 类中的 Ruby 的 -(减法)方法用于此目的,正如您在查看 Rails source code for TimeWithZone 时看到的那样。

    def -(other)
      if other.acts_like?(:time)
        to_time - other.to_time
      elsif duration_of_variable_length?(other)
        method_missing(:-, other)
      else
        result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
        result.in_time_zone(time_zone)
      end
    end
    

    根据Ruby docs,它返回一个浮点数。

    Difference — 以秒为单位返回时间差值作为浮点数 和 other_time,或以数字形式减去给定的秒数 从时间开始。

    【讨论】:

    • 所以它保留半秒,毫秒等?我怎样才能在不减法的情况下检查它们?
    • Time.now.to_i 返回秒数,Time.now.to_f 返回毫秒数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2012-04-23
    • 2011-11-22
    相关资源
    最近更新 更多