Search code examples
ruby-on-railsactivesupport

How ActiveSupport TimeWithZone retains values?


I tried something like that:

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

While when I tried:

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

So from where this float number?


Solution

  • Ruby's - (subtraction) method from the Time class is used for this as you can see looking at the 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
    

    As per the Ruby docs it returns a float.

    Difference — Returns a difference in seconds as a Float between time and other_time, or subtracts the given number of seconds in numeric from time.