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)
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'
Ruby on Rails retrieve datetime by converting it from UTC to user's time zone from database by querying date
If you store the datetime you can use it for that query using beginning_of_day
and end_of_day
methods on the time with timezone
date = Time.parse('Wed, 19 Nov 2014 19:23:59 UTC +00:00')
# => 2014-11-19 19:23:59 UTC
d = date.in_time_zone('Paris')
# => Wed, 19 Nov 2014 20:23:59 CET +01:00
User.where(created_at: (d.beginning_of_day..d.end_of_day)).count
# (46.5ms) SELECT COUNT(*) FROM "users" WHERE ("users"."created_at" BETWEEN '2014-11-18 23:00:00.000000' AND '2014-11-19 22:59:59.999999')
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)")
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.
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 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)')
Converting UTC to user preferred timezone on server side in Rails
After debugging for another hour, I figured out my mistake.
In the time_formats.rb
file where I am trying to set the time zone to the user's preference, I used the following:
Time::DATE_FORMATS[:default] = in_time_zone("%I:%M %p")
The in_time_zone
was causing the problem. I am already setting using the Application Controller to modify the time to the user's setting with current_user.timezone : nil
. By changing my time_formats.rb
to:
Time::DATE_FORMATS[:default] = "%I:%M %p"
I am now showing the correct time based on the user settings, and I can push to Heroku successfully while letting the Application Controller do the work.
Related Topics
How to Ruby on Rails Authentication with Ldap
The Command Rbenv Install Is Missing
Find Out If an Ip Is Within a Range of Ips
Does Ruby Have a String.Startswith("Abc") Built in Method
Setting Up the Logger in Rails 3
Rails - Invalid Authenticity Token After Deploy
Rails 4 Before_Action, Pass Parameters to Invoked Method
How to Run Rake Tasks Within My Rails Application
Getting Ruby 1.8.7 Installed on Mountain Lion (10.8)
How to Authorize a Service Account for Google Calendar API in Ruby
Passing a Hash to a Function ( *Args ) and Its Meaning
Installing Ruby 1.9.1 on Ubuntu
What's the Opposite of Chr() in Ruby
Rails 4 Error R14 on Heroku (Memory Quota Exceeded)
Rails-Like Database Migrations
Is It Idiomatic Ruby to Add an Assert( ) Method to Ruby's Kernel Class