The behavior I'm observing with the Mongoid adapter is that it'll save 'time' fields with the current system timezone into the database. Note that it's the system time and not Rail's environment's Time.zone. If I change the system timezone, then subsequent saves will pick up the current system timezone.
# system currently at UTC -7
#record.time_attribute = Time.now.utc
#record.save
# in mongo, the value is "time_attribute" : "Mon May 17 2010 12:00:00 GMT-0700 (QYZST)"
#record.reload.time_attribute.utc? # false
Try setting the use_utc mongoid config parameter to true.
It tells Mongoid that you want to return times in UTC:
http://github.com/durran/mongoid/blob/master/lib/mongoid/config.rb#L22
Related
I want to parse a string to a Time object in Rails. This string is in another timezone than the default app timezone. So now, when I parse the string I first have to store the current/default time zone, change the time zone, parse the string and change the time zone back to default. That's 4 lines of code to to one thing:
current_timezone = Time.zone
Time.zone = "Target time zone"
Time.zone.parse("Tue Nov 23 23:29:57 2010")
Time.zone = current_timezone
Is there a way to tell Rails inside the parse command which time zone to use?
Time.in_zone allows you to do this a little more idiomatically.
# Acting with the rails default timezone
Time.use_zone("America/New_York") do
# Acting with the target timezone
Time.zone.parse("Tue Nov 23 23:29:57 2010") #=> Tue, 23 Nov 2010 23:29:57 EST -05:00
end
# Acting with the rails default timezone
I am working on a rail4 app. Where I want to store dates in all mysql tables in UTC. However I store user's timezone in a specific table, called users. When user logs in, I get user's timezone form user table and save in session.
I am able to save date in all tables in UTC as default value of config.time_zone is UTC for activerecords and activemodels. But while displaying I want to show dates in user's timezone. As well as, when any user inputs a date/time in any html form, then I want to save it in the equivalent UTC format.
What is the best way to achieve this?
Rails, activerecord and MySQL will save all the timestamp fields in UTC. Without you having to do anything.
In your application.rb file where the configuration of the Application is done, you define the default time zone if you want the display of timestamps to take place on time zone different from UTC.
Hence
config.time_zone = 'Central Time (US & Canada)'
will display the timestamp fields (without you having to do anything special in other piece of code) using the Central Time.
When you want each of your users to have timestamps displayed in different time zone you can store the time zone in a column along side the user data. The column can be called time_zone and can contain the string of the user preferred time zone.
But, you have to tell the timestamp object to display itself to the specific timezone. This is done with the help of the method in_time_zone(timezone) that DateTime object responds to.
Example (when the default time zone is UTC):
1.9.3-p194 :004 > d = DateTime.new(2012, 9, 1, 6, 30, 0)
=> Sat, 01 Sep 2012 06:30:00 +0000
1.9.3-p194 :005 > d.in_time_zone("Central Time (US & Canada)")
=> Sat, 01 Sep 2012 01:30:00 CDT -05:00
Or you can change the time zone globally for the request at hand on a before or around filter. There is a documentation on internet if you do a google on that.
Read also this one: http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html
for various alternatives to approach the problem.
You could store the time in UTC, and store the timezone separately. Timezones are commonly stored as a UTC-offset in seconds (seconds are the SI unit of time).
Then you can display it like so:
utime = Time.now.utc.to_i # this value can be any format that Time.at can understand. In this example I'll use a unix timestamp in UTC. Chances are any time format you store in your DB will work.
=> 1375944780
time = Time.at(utime) # parses the time value (by default, the local timezone is set, e.g. UTC+08:00)
=> 2013-08-08 14:53:00 +0800
time_in_brisbane = time.in_time_zone(ActiveSupport::TimeZone[36000]) # sets the timezone, in this case to UTC+10:00 (see http://stackoverflow.com/a/942865/72176)
=> Thu, 08 Aug 2013 16:53:00 EST +10:00
time_brisbane.strftime("%d %b %Y, %l:%M %p %z") # format with strftime however you like!
=> "08 Aug 2013, 4:53 PM +1000"
I've been trying to change the timezone for a user session using the Time.zone method. I get the correct date and time when I do Time.zone.now but when I do a select query using ActiveRecord::Base.connection.select_all, the datetime columns in the result are always in UTC. What do I need to do so that all the select queries return data in the timezone that was set using the Time.zone method, without changing the views? Please help.
It's easiest to convert the Time to the local timezone with ruby.
Time.now.in_time_zone()
use it as such.
Time.now.in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
You can give the function a timezone string, or an UTC offset
http://apidock.com/rails/Time/in_time_zone
i've got a Course model, which has a datetime attribute. If I look at it from the database i get one time, and if i look at it from the object i get a different date & time.
>> Course.last.attribute_for_inspect :datetime
=> "\"2012-01-04 01:00:00\""
>> Course.last.datetime
=> Tue, 03 Jan 2012 19:00:00 CST -06:00
Does anyone know why this value is different, and what I can do to fix it? The time from Course.last.datetime is correct, but my queries on the course table aren't working correctly due to the mix-up.
From the fine manual:
attribute_for_inspect(attr_name)
Returns an #inspect-like string for the value of the attribute attr_name.
[...]
Date and Time attributes are returned in the :db format.
So, when attribute_for_inspect is used for a datetime, it will return the string that the database uses for that value. Rails stores times in the database in UTC and any sensible database will use ISO 8601 for formatting timestamps on the way in and out.
2012-01-04 01:00:00 is the UTC timestamp in ISO 8601 format. When Rails returns a datetime, it converts it to an ActiveSupport::TimeWithZone instance and includes a timezone adjustment based on the timezone that you have configured in your application.rb. You're using the CST timezone and that's six hours behind UTC; subtracting six hours from 01:00 gives you 19:00 and you lose a day from crossing midnight. The human friendly format, Tue, 03 Jan 2012 19:00:00 CST -06:00, is just how ActiveSupport::TimeWithZone represents itself when inspected and the console uses x.inspect to display x.
As far as fixing your queries goes, just use t.utc before sending in a time t and you should be good.
Configuring your Rails App Timezone in application.rb
set config.active_record.default_timezone to :local as it is set to :utc by default in the application.rb
paste this code in your application.rb
config.active_record.default_timezone = :local #or :utc
config.time_zone = "Singapore" #your timezone
I am migrating a Perl-based web application to Rails. The old application stores dates in a MySql database in local (Pacific) time. For example, there is a created field that might have the value 06/06/2008 14:00:00 representing 2:00 PM June 6, 2008 (PDT) whereas 02/02/2002 06:30:00 represents 6:00 AM February 2, 2002 (PST).
I have written a rake task to take all the old data and import it into the new database. The date in the new database still looks like 06/06/2008 14:00:00 but, of course, my Rails application interprets this as UTC.
The migrating task looks like this:
# Migrating old events in Perl application to new events in Rails
oldevents = OldEvent.all
oldevents.each do |oldevent|
newevent = Event.convert_old_event_to_newevent(oldevent)
newevent.save!
end
The interesting code is in the static method Event.convert_old_event_to_newevent:
def Event.convert_old_event_to_newevent(oldevent)
...
# If the "created" field in the old db contains '06/06/2008 14:00:00' (meaning
# 2:00 PM PDT (since June is during daylight savings time) then the
# "created_at" field in the new database will contain the same string which
# Rails interprets as 2:00 PM GMT.
newevent.created_at = oldevent.created
...
return newevent
end
So, in the migration process, before storing the dates in the new database I need to read the date/times from the old database, convert them to UTC, and then store that in the new database.
How can that be done?
>> Time.local(*'06/06/2008 14:00:00'.split(/[:\/ ]/).values_at(2,0,1,3..5)).utc
=> Fri Jun 06 21:00:00 UTC 2008
This obviously returns a Ruby core library Time object that can be formatted any way you like.
If your time zone is not already Pacific, run your rake import task like:
$ TZ=PST rake initdb:import # whatever
Now, Rails defines a type called DateTime which you may need, and it wants real integer parameters, so:
DateTime.civil_from_format :local, *'06/06/2008 14:00:00'.split(/[:\/ ]/).map(&:to_i).values_at(2,0,1,3..5)