aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
diff options
context:
space:
mode:
authorGilad Zohari <gzohari@gmail.com>2013-07-31 21:02:01 +0300
committerGilad Zohari <gzohari@gmail.com>2013-08-01 00:27:25 +0300
commit3102a9aa4cfd747e116adc12dce6f5faf1453ea9 (patch)
tree241ba59b12fc66ad4ce1b2ddd3bba722c0cbcc94 /activesupport/lib/active_support/core_ext/date_and_time/zones.rb
parent742d1f2eda24dd411e018835680645d3921883f5 (diff)
downloadrails-3102a9aa4cfd747e116adc12dce6f5faf1453ea9.tar.gz
rails-3102a9aa4cfd747e116adc12dce6f5faf1453ea9.tar.bz2
rails-3102a9aa4cfd747e116adc12dce6f5faf1453ea9.zip
Refactor Date, Time, DateTime timezone methods
Similar implementations of #in_time_zone exists for Date, Time and DateTime so method is extracted into its own module. Also some logic is extracted into private method.
Diffstat (limited to 'activesupport/lib/active_support/core_ext/date_and_time/zones.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/zones.rb41
1 files changed, 41 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
new file mode 100644
index 0000000000..96c6df9407
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
@@ -0,0 +1,41 @@
+module DateAndTime
+ module Zones
+ # Returns the simultaneous time in <tt>Time.zone</tt> if a zone is given or
+ # if Time.zone_default is set. Otherwise, it returns the current time.
+ #
+ # Time.zone = 'Hawaii' # => 'Hawaii'
+ # DateTime.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ # Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
+ #
+ # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
+ # instead of the operating system's time zone.
+ #
+ # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
+ # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
+ #
+ # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
+ # DateTime.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
+ # Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
+ def in_time_zone(zone = ::Time.zone)
+ time_zone = ::Time.find_zone! zone
+ time = acts_like?(:time) ? self : nil
+
+ if time_zone
+ time_with_zone(time, time_zone)
+ else
+ time || self.to_time
+ end
+ end
+
+ private
+
+ def time_with_zone(time, zone)
+ if time
+ ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
+ else
+ ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
+ end
+ end
+ end
+end
+