代码之家  ›  专栏  ›  技术社区  ›  Ahmed Salah

ActiveSupport TimeWithZone如何保留值?

  •  0
  • Ahmed Salah  · 技术社区  · 6 年前

    我试过这样的方法:

    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"]
    

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

    0 回复  |  直到 6 年前
        1
  •  0
  •   Eyeslandic    6 年前

    露比 - (减法) Time 类用于此,您可以看到 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返回以秒为单位的差,作为时间之间的浮点 和其他时间,或用数字减去给定的秒数 有时。