Rails: convert UTC DateTime to another time zone

Ruby on-RailsRubyDatetimeRuntime

Ruby on-Rails Problem Overview


In Ruby/Rails, how do I convert a UTC DateTime to another time zone?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

time.in_time_zone(time_zone)

Example:

zone = ActiveSupport::TimeZone.new("Central Time (US & Canada)")
Time.now.in_time_zone(zone)

or just

Time.now.in_time_zone("Central Time (US & Canada)")

You can find the names of the ActiveSupport time zones by doing:

ActiveSupport::TimeZone.all.map(&:name)
# or for just US
ActiveSupport::TimeZone.us_zones.map(&:name)

Solution 2 - Ruby on-Rails

if Time.zone it's your desired time zone then you can use @date.to_time.to_datetime

> @date
=> Tue, 02 Sep 2014 23:59:59 +0000
> @date.class
=> DateTime
> @date.to_time
=> 2014-09-02 12:59:59 -1100
> @date.to_time.to_datetime
=> Tue, 02 Sep 2014 12:59:59 -1100 

Solution 3 - Ruby on-Rails

In plain ruby, with only require 'date', use the new_offset method:

require 'date'

d=DateTime.parse('2000-01-01 12:00 +0200')
l=d.new_offset('-0700')
u=l.new_offset('UTC')
puts "#{u.strftime('%a %F %T %Z')} ❖ #{l.strftime('%a %F %T %Z')}"

Tested with ruby 2.3.7 that came standard on Mac OS X 10.13.

Solution 4 - Ruby on-Rails

Try ActiveSupport's http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html">TimeWithZone</a> objects manipulated with TimeZone. ActiveSupport also provides the in_time_zone method for converting a UTC time to a specified TimeZone time zone. mckeed's answer shows the code.

Solution 5 - Ruby on-Rails

Just in case, if you are dealing with ActiveRecord object in Rails.

It might be a good idea to use Time.use_zone for a per request basis timezone that overrides the default timezone set in config.time_zone

More details I explain at https://stackoverflow.com/a/25055692/542995

Solution 6 - Ruby on-Rails

I'm using simple_form in Rails 4 and I just added the input field as

<%= f.input :time_zone, :as => :time_zone %>

with the migration

class AddTimeZoneColumnToTextmessage < ActiveRecord::Migration
  def change
    add_column :textmessages, :time_zone, :string
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew JohnsonView Question on Stackoverflow
Solution 1 - Ruby on-RailsmckeedView Answer on Stackoverflow
Solution 2 - Ruby on-RailsvladCovaliovView Answer on Stackoverflow
Solution 3 - Ruby on-RailsjbylerView Answer on Stackoverflow
Solution 4 - Ruby on-RailsFredView Answer on Stackoverflow
Solution 5 - Ruby on-RailszdkView Answer on Stackoverflow
Solution 6 - Ruby on-RailsmaudulusView Answer on Stackoverflow