A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are limited to UTC and the system’s ENV['TZ'] zone.

You shouldn’t ever need to create a TimeWithZone instance directly via new . Instead use methods local, parse, at and now on TimeZone instances, and in_time_zone on Time and DateTime instances. Examples:

  Time.zone = 'Eastern Time (US & Canada)'        # => 'Eastern Time (US & Canada)'
  Time.zone.local(2007, 2, 10, 15, 30, 45)        # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  Time.zone.parse('2007-02-01 15:30:45')          # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  Time.zone.at(1170361845)                        # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  Time.zone.now                                   # => Sun, 18 May 2008 13:07:55 EDT -04:00
  Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone  # => Sat, 10 Feb 2007 15:30:45 EST -05:00

See Time and TimeZone for further documentation of these methods.

TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangeable. Examples:

  t = Time.zone.now                     # => Sun, 18 May 2008 13:27:25 EDT -04:00
  t.hour                                # => 13
  t.dst?                                # => true
  t.utc_offset                          # => -14400
  t.zone                                # => "EDT"
  t.to_s(:rfc822)                       # => "Sun, 18 May 2008 13:27:25 -0400"
  t + 1.day                             # => Mon, 19 May 2008 13:27:25 EDT -04:00
  t.beginning_of_year                   # => Tue, 01 Jan 2008 00:00:00 EST -05:00
  t > Time.utc(1999)                    # => true
  t.is_a?(Time)                         # => true
  t.is_a?(ActiveSupport::TimeWithZone)  # => true
Methods
Included Modules
Attributes
[R] time_zone
Public Class methods
name()
      # File activesupport/lib/active_support/time_with_zone.rb, line 36
36:     def self.name
37:       'Time' # Report class name as 'Time' to thwart type checking
38:     end
new(utc_time, time_zone, local_time = nil, period = nil)
      # File activesupport/lib/active_support/time_with_zone.rb, line 43
43:     def initialize(utc_time, time_zone, local_time = nil, period = nil)
44:       @utc, @time_zone, @time = utc_time, time_zone, local_time
45:       @period = @utc ? period : get_period_and_ensure_valid_local_time
46:     end
Public Instance methods
+(other)
       # File activesupport/lib/active_support/time_with_zone.rb, line 200
200:     def +(other)
201:       # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
202:       # otherwise move forward from #utc, for accuracy when moving across DST boundaries
203:       if duration_of_variable_length?(other)
204:         method_missing(:+, other)
205:       else
206:         result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
207:         result.in_time_zone(time_zone)
208:       end
209:     end
-(other)
       # File activesupport/lib/active_support/time_with_zone.rb, line 211
211:     def -(other)
212:       # If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
213:       # otherwise move backwards #utc, for accuracy when moving across DST boundaries
214:       if other.acts_like?(:time)
215:         utc.to_f - other.to_f
216:       elsif duration_of_variable_length?(other)
217:         method_missing(:-, other)
218:       else
219:         result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
220:         result.in_time_zone(time_zone)
221:       end
222:     end
<=>(other)

Use the time in UTC for comparisons.

       # File activesupport/lib/active_support/time_with_zone.rb, line 176
176:     def <=>(other)
177:       utc <=> other
178:     end
acts_like_time?()

So that self acts_like?(:time).

       # File activesupport/lib/active_support/time_with_zone.rb, line 284
284:     def acts_like_time?
285:       true
286:     end
advance(options)
       # File activesupport/lib/active_support/time_with_zone.rb, line 238
238:     def advance(options)
239:       # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
240:       # otherwise advance from #utc, for accuracy when moving across DST boundaries
241:       if options.values_at(:years, :weeks, :months, :days).any?
242:         method_missing(:advance, options)
243:       else
244:         utc.advance(options).in_time_zone(time_zone)
245:       end
246:     end
ago(other)
       # File activesupport/lib/active_support/time_with_zone.rb, line 234
234:     def ago(other)
235:       since(-other)
236:     end
as_json(options = nil)

Coerces time to a string for JSON encoding. The default format is ISO 8601. You can get %Y/%m/%d %H:%M:%S +offset style by setting ActiveSupport::JSON::Encoding.use_standard_json_time_format to false.

Examples

  # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
  Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
  # => "2005-02-01T15:15:10Z"

  # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
  Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
  # => "2005/02/01 15:15:10 +0000"
       # File activesupport/lib/active_support/time_with_zone.rb, line 130
130:     def as_json(options = nil)
131:       if ActiveSupport::JSON::Encoding.use_standard_json_time_format
132:         xmlschema
133:       else
134:         %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
135:       end
136:     end
between?(min, max)
       # File activesupport/lib/active_support/time_with_zone.rb, line 180
180:     def between?(min, max)
181:       utc.between?(min, max)
182:     end
dst?()
This method is also aliased as isdst
      # File activesupport/lib/active_support/time_with_zone.rb, line 79
79:     def dst?
80:       period.dst?
81:     end
eql?(other)
       # File activesupport/lib/active_support/time_with_zone.rb, line 196
196:     def eql?(other)
197:       utc == other
198:     end
formatted_offset(colon = true, alternate_utc_string = nil)
      # File activesupport/lib/active_support/time_with_zone.rb, line 95
95:     def formatted_offset(colon = true, alternate_utc_string = nil)
96:       utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
97:     end
freeze()
       # File activesupport/lib/active_support/time_with_zone.rb, line 294
294:     def freeze
295:       period; utc; time # preload instance variables before freezing
296:       super
297:     end
future?()
       # File activesupport/lib/active_support/time_with_zone.rb, line 192
192:     def future?
193:       utc.future?
194:     end
httpdate()
       # File activesupport/lib/active_support/time_with_zone.rb, line 146
146:     def httpdate
147:       utc.httpdate
148:     end
in_time_zone(new_zone = ::Time.zone)

Returns the simultaneous time in Time.zone, or the specified zone.

      # File activesupport/lib/active_support/time_with_zone.rb, line 68
68:     def in_time_zone(new_zone = ::Time.zone)
69:       return self if time_zone == new_zone
70:       utc.in_time_zone(new_zone)
71:     end
inspect()
       # File activesupport/lib/active_support/time_with_zone.rb, line 104
104:     def inspect
105:       "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
106:     end
is_a?(klass)

Say we’re a Time to thwart type checking.

This method is also aliased as kind_of?
       # File activesupport/lib/active_support/time_with_zone.rb, line 289
289:     def is_a?(klass)
290:       klass == ::Time || super
291:     end
localtime()

Returns a Time.local() instance of the simultaneous time in your system’s ENV['TZ'] zone

This method is also aliased as getlocal
      # File activesupport/lib/active_support/time_with_zone.rb, line 74
74:     def localtime
75:       utc.getlocal
76:     end
marshal_dump()
       # File activesupport/lib/active_support/time_with_zone.rb, line 299
299:     def marshal_dump
300:       [utc, time_zone.name, time]
301:     end
marshal_load(variables)
       # File activesupport/lib/active_support/time_with_zone.rb, line 303
303:     def marshal_load(variables)
304:       initialize(variables[0].utc, ::Time.__send__(:get_zone, variables[1]), variables[2].utc)
305:     end
method_missing(sym, *args, &block)

Send the missing method to time instance, and wrap result in a new TimeWithZone with the existing time_zone.

       # File activesupport/lib/active_support/time_with_zone.rb, line 315
315:     def method_missing(sym, *args, &block)
316:       result = time.__send__(sym, *args, &block)
317:       result.acts_like?(:time) ? self.class.new(nil, time_zone, result) : result
318:     end
past?()
       # File activesupport/lib/active_support/time_with_zone.rb, line 184
184:     def past?
185:       utc.past?
186:     end
period()

Returns the underlying TZInfo::TimezonePeriod.

      # File activesupport/lib/active_support/time_with_zone.rb, line 63
63:     def period
64:       @period ||= time_zone.period_for_utc(@utc)
65:     end
respond_to?(sym, include_priv = false)

Ensure proxy class responds to all methods that underlying time instance responds to.

       # File activesupport/lib/active_support/time_with_zone.rb, line 308
308:     def respond_to?(sym, include_priv = false)
309:       # consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
310:       return false if sym.to_s == 'acts_like_date?'
311:       super || time.respond_to?(sym, include_priv)
312:     end
rfc2822()
This method is also aliased as rfc822
       # File activesupport/lib/active_support/time_with_zone.rb, line 150
150:     def rfc2822
151:       to_s(:rfc822)
152:     end
since(other)
       # File activesupport/lib/active_support/time_with_zone.rb, line 224
224:     def since(other)
225:       # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
226:       # otherwise move forward from #utc, for accuracy when moving across DST boundaries
227:       if duration_of_variable_length?(other)
228:         method_missing(:since, other)
229:       else
230:         utc.since(other).in_time_zone(time_zone)
231:       end
232:     end
strftime(format)

Replaces %Z and %z directives with zone and formatted_offset, respectively, before passing to Time#strftime, so that zone information is correct

       # File activesupport/lib/active_support/time_with_zone.rb, line 170
170:     def strftime(format)
171:       format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false))
172:       time.strftime(format)
173:     end
time()

Returns a Time or DateTime instance that represents the time in time_zone.

      # File activesupport/lib/active_support/time_with_zone.rb, line 49
49:     def time
50:       @time ||= period.to_local(@utc)
51:     end
to_a()
       # File activesupport/lib/active_support/time_with_zone.rb, line 260
260:     def to_a
261:       [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
262:     end
to_datetime()
       # File activesupport/lib/active_support/time_with_zone.rb, line 279
279:     def to_datetime
280:       utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
281:     end
to_f()
       # File activesupport/lib/active_support/time_with_zone.rb, line 264
264:     def to_f
265:       utc.to_f
266:     end
to_i()
This method is also aliased as hash tv_sec
       # File activesupport/lib/active_support/time_with_zone.rb, line 268
268:     def to_i
269:       utc.to_i
270:     end
to_s(format = :default)

:db format outputs time in UTC; all others output time in local. Uses TimeWithZone’s strftime, so %Z and %z work correctly.

This method is also aliased as to_formatted_s
       # File activesupport/lib/active_support/time_with_zone.rb, line 157
157:     def to_s(format = :default)
158:       if format == :db
159:         utc.to_s(format)
160:       elsif formatter = ::Time::DATE_FORMATS[format]
161:         formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
162:       else
163:         "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
164:       end
165:     end
to_time()

A TimeWithZone acts like a Time, so just return self.

       # File activesupport/lib/active_support/time_with_zone.rb, line 275
275:     def to_time
276:       self
277:     end
to_yaml(options = {})
       # File activesupport/lib/active_support/time_with_zone.rb, line 138
138:     def to_yaml(options = {})
139:       if options.kind_of?(YAML::Emitter)
140:         utc.to_yaml(options)
141:       else
142:         time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z'))
143:       end
144:     end
today?()
       # File activesupport/lib/active_support/time_with_zone.rb, line 188
188:     def today?
189:       time.today?
190:     end
usec()
       # File activesupport/lib/active_support/time_with_zone.rb, line 256
256:     def usec
257:       time.respond_to?(:usec) ? time.usec : 0
258:     end
utc()

Returns a Time or DateTime instance that represents the time in UTC.

This method is also aliased as comparable_time getgm getutc gmtime
      # File activesupport/lib/active_support/time_with_zone.rb, line 54
54:     def utc
55:       @utc ||= period.to_utc(@time)
56:     end
utc?()
This method is also aliased as gmt?
      # File activesupport/lib/active_support/time_with_zone.rb, line 84
84:     def utc?
85:       time_zone.name == 'UTC'
86:     end
utc_offset()
This method is also aliased as gmt_offset gmtoff
      # File activesupport/lib/active_support/time_with_zone.rb, line 89
89:     def utc_offset
90:       period.utc_total_offset
91:     end
xmlschema(fraction_digits = 0)
This method is also aliased as iso8601
       # File activesupport/lib/active_support/time_with_zone.rb, line 108
108:     def xmlschema(fraction_digits = 0)
109:       fraction = if fraction_digits > 0
110:         ".%i" % time.usec.to_s[0, fraction_digits]
111:       end
112: 
113:       "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
114:     end
zone()

Time uses zone to display the time zone abbreviation, so we’re duck-typing it.

       # File activesupport/lib/active_support/time_with_zone.rb, line 100
100:     def zone
101:       period.zone_identifier.to_s
102:     end
Private Instance methods
duration_of_variable_length?(obj)
       # File activesupport/lib/active_support/time_with_zone.rb, line 338
338:       def duration_of_variable_length?(obj)
339:         ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include? p[0] }
340:       end
get_period_and_ensure_valid_local_time()
       # File activesupport/lib/active_support/time_with_zone.rb, line 321
321:       def get_period_and_ensure_valid_local_time
322:         # we don't want a Time.local instance enforcing its own DST rules as well,
323:         # so transfer time values to a utc constructor if necessary
324:         @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
325:         begin
326:           @time_zone.period_for_local(@time)
327:         rescue ::TZInfo::PeriodNotFound
328:           # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
329:           @time += 1.hour
330:           retry
331:         end
332:       end
transfer_time_values_to_utc_constructor(time)
       # File activesupport/lib/active_support/time_with_zone.rb, line 334
334:       def transfer_time_values_to_utc_constructor(time)
335:         ::Time.utc_time(time.year, time.month, time.day, time.hour, time.min, time.sec, time.respond_to?(:usec) ? time.usec : 0)
336:       end