Convert Utc to Local Time in Rails 3

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones.
To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

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

how can i convert utc time to local time timezone with +05:30

%w|+05:30 +10:00|.map do |time_zone|
hours, mins = time_zone.split(':').map(&:to_i).map(&:abs)
sign = time_zone[0] == '-' ? -1 : 1
Time.now.in_time_zone(ActiveSupport::TimeZone[(hours + 1.0 * mins / 60]) * sign)
end
#⇒ [Wed, 06 Jul 2016 12:54:10 IST +05:30, Wed, 06 Jul 2016 17:24:10 AEST +10:00]

Convert local time to UTC in Rails

local to utc

created_at.utc

utc to local

created_at.localtime

Ruby converting UTC to user's time zone

I added a method in_timezone method in Time class as follows:

class Time
require 'tzinfo'
# tzstring e.g. 'America/Los_Angeles'
def in_timezone tzstring
tz = TZInfo::Timezone.get tzstring
p = tz.period_for_utc self
e = self + p.utc_offset
"#{e.strftime("%m/%d/%Y %I:%M %p")} #{p.zone_identifier}"
end
end

How to use it:

t = Time.parse("2013-11-01T21:19:00Z")  
t.in_timezone 'America/Los_Angeles'

How to convert UTC to EST/EDT in Ruby?

The best approach would be to use TZInfo.

require 'tzinfo'
require 'time'

def utc_to_eastern utc
tz = TZInfo::Timezone.get("America/New_York")
tz.to_local(Time.parse(utc)).strftime('%Y-%m-%d %H:%M:%S')
end

utc_to_eastern "2020-02-02 00:00:00 UTC" => "2020-02-01 19:00:00"
utc_to_eastern "2020-04-02 00:00:00 UTC" => "2020-04-01 20:00:00"

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)

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)')


Related Topics



Leave a reply



Submit