1 module ActiveSupport
#:nodoc:
2 module CoreExtensions
#:nodoc:
5 def self.included(base
) #:nodoc:
6 base
.extend(ClassMethods
) if base
== ::Time # i.e., don't include class methods in DateTime
10 attr_accessor
:zone_default
12 # Returns the TimeZone for the current request, if this has been set (via Time.zone=).
13 # If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
15 Thread
.current
[:time_zone] || zone_default
18 # Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
20 # This method accepts any of the following:
22 # * A Rails TimeZone object.
23 # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
24 # * A TZInfo::Timezone object.
25 # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
27 # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt>
28 # just needs to return a string identifying the user's preferred TimeZone:
30 # class ApplicationController < ActionController::Base
31 # before_filter :set_time_zone
34 # Time.zone = current_user.time_zone
38 Thread
.current
[:time_zone] = get_zone(time_zone
)
41 # Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
42 def use_zone(time_zone
)
43 old_zone
, ::Time.zone
= ::Time.zone
, get_zone(time_zone
)
46 ::Time.zone
= old_zone
49 # Returns <tt>Time.zone.now</tt> when <tt>config.time_zone</tt> is set, otherwise just returns <tt>Time.now</tt>.
51 ::Time.zone_default
? ::Time.zone
.now
: ::Time.now
55 def get_zone(time_zone
)
56 return time_zone
if time_zone
.nil? || time_zone
.is_a
?(TimeZone
)
57 # lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
58 unless time_zone
.respond_to
?(:period_for_local)
59 time_zone
= TimeZone
[time_zone
] || TZInfo
::Timezone.get(time_zone
) rescue nil
61 # Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
63 time_zone
.is_a
?(TimeZone
) ? time_zone
: TimeZone
.create(time_zone
.name
, nil, time_zone
)
68 # Returns the simultaneous time in <tt>Time.zone</tt>.
70 # Time.zone = 'Hawaii' # => 'Hawaii'
71 # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
73 # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
74 # instead of the operating system's time zone.
76 # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
77 # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
79 # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
80 def in_time_zone(zone
= ::Time.zone
)
81 ActiveSupport
::TimeWithZone.new(utc
? ? self : getutc
, ::Time.__send__(:get_zone, zone
))