Convert Time from One Time Zone to Another in Rails

Convert Time from one time zone to another in Rails

Use the in_time_zone method of the DateTime class

Loading development environment (Rails 2.3.2)
>> now = DateTime.now.utc
=> Sun, 06 Sep 2009 22:27:45 +0000
>> now.in_time_zone('Eastern Time (US & Canada)')
=> Sun, 06 Sep 2009 18:27:45 EDT -04:00
>> quit

So for your particular example

Annotation.last.created_at.in_time_zone('Eastern Time (US & Canada)')

Rails: Convert future meeting time in one time zone to another time zone

It's .parse()

Time.zone.parse(params["meetingTime"]).in_time_zone(attendeeZone)

Alternatively, if you assign it to a model, then it will be parsed automatically already.

Rails: convert UTC DateTime to another time zone

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)

How to convert time with timezone in ruby

There's no method for that, however you can make one for yourself:

class Time
require 'time'
def self.by_offset(offset)
at(now + zone_offset(offset))
end
end

Now, you can:

Time.by_offset('PST')
#=> 2014-11-03 10:11:14 +0530
Time.now
#=> 2014-11-03 18:11:13 +0530

Tested with 1.9.2, 2.0.0, and 2.1.2 Rubies(MRI).

How to convert time to specific timezone in Rails?

Time can be parsed from string as per current time zone using Time.zone.parse

Time.zone.parse(time_string)

But You need to set the required timezone before as below:

Time.zone = 'Mumbai'

After setting up the timezone all the parsing will be done in that time zone.

I you need to have different timezone for different users then set specific timezone for user in before_filter in ApplicationController.
eg:
Time.zone = current_user.time_zone # here the time_zone method should return the timezone name for current_user

Now wherever you want to display time in the user timezone simply call in_time_zone method on time object.
eg:

2.0.0-p353 :003 > Time.zone
=> #<ActiveSupport::TimeZone:0xa3a75a0 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=nil>
2.0.0-p353 :004 > time = Time.zone.parse('15/02/2014 10:05 AM')
=> Sat, 15 Feb 2014 10:05:00 UTC +00:00
2.0.0-p353 :005 > Time.zone = 'Mumbai'
=> "Mumbai"
2.0.0-p353 :006 > time = Time.zone.parse('15/02/2014 10:05 AM')
=> Sat, 15 Feb 2014 10:05:00 IST +05:30

Convert date time in another timezone with offset value in ruby

Using Time::parse and Time#localtime:

require 'time'

t = Time.parse('2014-12-15T19:56:59Z')
#=> 2014-12-15 19:56:59 UTC

t.localtime('-06:00')
#=> 2014-12-15 13:56:59 -0600


Related Topics



Leave a reply



Submit