ActiveRecord DateTime field not matching object - ruby-on-rails

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

Related

Passing date from angular to rails

I have a problem with passing date from Angular to Rails. In my project i use datetimepicker directive (https://github.com/dalelotts/angular-bootstrap-datetimepicker) which is using moment js. So when i pick the date it looks like "Wed Aug 05 2015 11:55:00 GMT+0300 (EEST)". Then this date is passing to rails api and rails converts it in "2015-08-05T08:55:00.000Z". So i simply need that the time received by rails was 11:55:00 not 08:55:00.
You do need to realize that Wed Aug 05 2015 11:55:00 GMT+0300 is equal to 2015-08-05T08:55:00.000Z and that the later date is a translation to UTC of the first one.
To change the timezone in which Active Record saves in the database, you can use
# application.rb
config config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local
Warning! You really should think twice, even thrice, before saving times in the database in a non-UTC format.
Here's how you can find all available timezones
rake:time:all
More information: https://stackoverflow.com/a/32229086/4304188

Rails4: Saving and displaying date in user's 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"

Changing ActiveRecord timezone for a session

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

Rails timezone differences between Time and DateTime

I have the timezone set.
config.time_zone = 'Mountain Time (US & Canada)'
Creating a Christmas event from the console...
c = Event.new(:title => "Christmas")
using Time:
c.start = Time.new(2012,12,25)
=> 2012-12-25 00:00:00 -0700 #has correct offset
c.end = Time.new(2012,12,25).end_of_day
=> 2012-12-25 23:59:59 -0700 #same deal
using DateTime:
c.start = DateTime.new(2012,12,25)
=> Tue, 25 Dec 2012 00:00:00 +0000 # no offset
c.end = DateTime.new(2012,12,25).end_of_day
=> Tue, 25 Dec 2012 23:59:59 +0000 # same
I've carelessly been using DateTime thinking that input was assumed to be in the config.time_zone but there's no conversion when this gets saved to the db. It's stored just the same as the return values (formatted for the db).
Using Time is really no big deal but do I need to manually offset anytime I'm using DateTime and want it to be in the correct zone?
Yep. Time.new will intepret parameters as local time in the absence of a specific timezone, and DateTime.new will intepret parameters as UTC in the absence of a specific timezone. As documented. You may want to replace Time.new with Time.local for clarity throughout your code.
What you can do is use DateTime's mixins for Time to invoke Time.local(2012,12,25).to_datetime. But if the year/month/day is coming from a user/browser, then perhaps you should get the user's/browser's timezone instead of using your server's.
If you need to create a migration to fix existing data in the DB, new_date_time = Time.local(old_date_time.year, old_date_time.mon, old_date_time.mday, old_date_time.hour, old_date_time.min, old_date_time.sec).to_datetime

Which should I always parse date times with? DateTime, Time, Time.zone?

In Rails, I see I have a few options to parse a date and a date-time. What is the best practice for parsing dates for the sole purpose of persisting them into the DB via ActiveRecord? And why?
Time.zone.parse(...)
Time.parse(...)
DateTime.parse(...)
Go with Time.zone.parse if you just want to write into ActiveRecord.
DateTime should be avoided. If you're handling dates, you should use Date.parse instead.
Beyond that, it depends on whether the input comes with timezone information, what the current timezone is set to, and whether you want timezones in your data.
Time.zone.parse will return an ActiveSupport::TimeWithZone, defaulting to UTC.
> Time.zone.parse("12:30")
=> Thu, 10 May 2012 12:30:00 UTC +00:00
Time.parse will return a Time, with a zone if it's specified in the input, or the local TZ.
> Time.parse("12:30")
=> 2012-05-09 12:30:00 -0700
For a more detailed explanation of Ruby time comparisons and precision, read this blog post:
http://blog.solanolabs.com/rails-time-comparisons-devil-details-etc/
Times that are automatically set by ActiveRecord (e.g. created_at and updated_at) come back as ActiveSupport::TimeWithZone instances.
According to the documentation, ActiveSupport::TimeWithZone and Time have the same API, so Time is what I would use.
On an unrelated note, there are methods to_time and to_datetime that you can call on strings:
"2012-05-09".to_time # => 2012-05-09 00:00:00 UTC
"2012-05-09".to_datetime # => Wed, 09 May 2012 00:00:00 +0000

Resources