How to deal with UTC times and Rails/ActiveRecord - ruby-on-rails

I'm using Rails 3.2.8. When I generate a scaffold with a time field or datetime field. The HTML form field gets pre-populated with the current date/time in UTC. Great that it's pre-populated with the current date/time, but because it's in UTC, we have to change the time back 7 hours every time (which will sometimes require setting the day back 1 also, possibly month and year too). And then it seems the UTC time gets stored in the database, so I'll have issues displaying/editing it as well if I recorded it in our local time.
I looked at the Ruby documentation for the form helpers to deal with local time better, but I don't see anything relevant.
What's the best way to deal with editing and displaying dates and times in Rails?
UPDATE: To clarify, I like the idea that UTC time is stored in the database. I just want the time_select and datetime_select form helpers to edit the times in the user's local timezone. And, of course, I want to easily display the time in the user's local timezone.

You have to set the time zone to display on a per-user basis somewhere in a before/around_filter. This has to be done like:
Time.zone = "Kyiv"
An example can be found in its API: http://api.rubyonrails.org/classes/Time.html#method-c-zone-3D.
Run the rake time:zones:all to see all of them.
All the conversions has to be handled for you behind the scene.

This has helped me in the past. You can do things like:
Time.now.in_time_zone("Central Time (US & Canada)")
See Rails: convert UTC DateTime to another time zone

Related

Postgresql date difference in table and on web

I have weird situation with my PostgreSQL db date value.
On my web site I have calendar for selecting a date and when I select some future date like "2018-09-23" in PostgreSQL table column it is saved as "2018-09-22 22:00:00"?
Obviously I am missing something. On web site all the time it shows okay time "2018-09-23" but at the table it is minus one day as you see above. Why?
Rails stores DateTime fields in UTC, but without marking their time zone as UTC. This corresponds to the timestamp without time zone type in postgres. So if your time zone is +2, it'll store the time as UTC (+0).
In Rails, Time.zone will return the current local timezone (you can add logic to change this by user, for example). When persisting a datetime, Rails will automatically convert the current Time.zone to UTC. However, it doesn't use the Postgres type that actually includes the time zone data, so it relies on convention to convert back and forth to the user's time zone.
If you really only care about the date, use the date type in your migration instead of Timestamp or DateTime.
Times and dates have a lot of subtle quirks and the "right" behavior depends on your use case. In some applications, you need to deal with "local" time when considering date transitions, and sometimes you need to finesse your application or database logic to think in terms of local time and sometimes you care about UTC time.

rails - Store DateTime objects in same time zone as timestamps

When i save a DateTime schedule_time to the DB, it saves according to my local time, but the timestamps (created_at) are saved apparently in UTC (7 hours ahead of my pacific time)
So if i submit the form setting my schedule_time for right now it will be 7 hours different than my created_at.
i need to show many users their times in their own selected zone, and i also need to compare times against each other, so i want all db entries to be in the same zone. Testing on my machine, my user has his zone saved as Pacific (-7:00), but its saving schedule_time in local time, not really UTC, so when i try to display the time back like this:
#item.schedule_time.in_time_zone(#user.time_zone)
it actually takes the stored datetime and subtracts seven hours from it giving me 7 hours before i wanted. i think the best thing is to just store all the datetimes in a uniform way so i can compare them easily.
changing this value config.time_zone = 'UTC' does nothing to change the stored format of my datetime. it stores in my local time regardless, while storing the timepstamps in real UTC.
ive also tried to reformat the datetime before storing it, with in_time_zone(#user.time_zone) but it had no effect on the stored time.
if i can just get schedule_time stored in UTC just like my timestamps are stored i could make this work! any ideas?
If you want to store schedule_time converted to UTC before storing it in the database, you can include a before_save callback in your Item model to convert it as follows:
before_save { |item| item.schedule_time = item.schedule_time.utc }
sorry i was totally on the wrong track.
the issue was with the jquery date picker i was using (will_pickdate). it returns a date and time but with a +0000 time zone offset. by default, the picker autofills with the current local time, but when i submitted that, rails basically thought it was receiving a time in UTC and added it as my local time but with +0000.
in order to store the date properly i have to keep the time and date from the picker intact, but just shift the +0000 part to something appropriate:
my_time.change(offset: user_time_zone_offset)

Rails : Given that my database is in UTC, and my Time.zone US Eastern, how do I save a time in US Pacific?

(I'm using Rails 3.2.3 on Ruby MRI 1.9.2)
Everything is stored centrally in UTC. This is good. Each User has a 'timezone' property. My ApplicationController has a before filter to adjust Time.zone to the User's stored timezone. This is also good.
Given the above, if my User completes a datetime select with a time, that time is expected to be in Time.zone and Rails will automatically adjust and save this as UTC. This too, is good.
Now: I wish to enable my Users to fill out a time in another time zone and then have it stored as UTC. However, Rails is expecting the completed date time select to have been filled out in the (previously set by ApplicationController) Time.zone. Therefore Rails adjusts to UTC incorrectly.
How do I achieve my goal of saving a time that has been input as being in a third time zone?
Illustration:
My usage scenario is a User in Florida adjusting a date for a Document belonging to a Hotel on the West Coast. They are looking to enter a time for the West Coast.
I'm using jQuery to style text boxes with a styled picker, so I have a method to output a string to the text box:
<%= f.text_field(:created_at, :value => adjusted_to_hotel_time(#document.created_at), :class => 'text datetime_picker') %>
def adjusted_to_hotel_time(time)
time.in_time_zone(#current_hotel.timezone).to_s(:admin_jquery) # formatted for the jQuery datetime_picker text fields.
end
This is working perfectly, but Rails adjusts to UTC incorrectly when the #document is saved. I don't know what I don't know - how can I 'tag' the data entered in that field as being in #current_hotel.timezone, so that Rails will offset to UTC correctly when it saves the parent object?
Cracked it!
Basically, the string that is submitted to params is representing a time in a Hotel's timezone. We have to use the built in 'use_zone' method to temporarily set the global Time.zone to that Hotel's.
We then pass the method a block where we produce the value that Rails is expecting, by using the timezone of the Hotel, rather than the User. That means that Rails' conversion to UTC results in the correct time in the db - as the time entered on the form has been converted to the Users timezone. The offsets have cancelled each other out, effectively.
#document.created_at = Time.use_zone(#current_hotel.timezone) {Time.zone.parse("#{params[:document][:created_at]}").in_time_zone(#current_hotel.timezone)}
We're basically changing the timezone of the Time object here without converting the actual time of that Time object when the timezone changes. (Good luck parsing that sentence!)
This looks to be working fine for me, but I've been looking at this for too long and I'd love to see a better way/more Rails-ey way of doing this!
The datetime column type only stores a date and time, but not the time-zone. You may need to create a secondary column to preserve the time zone used to interpret the UTC time saved there.
These two values could combine to re-create your initial input.

Rails time type and time zones

I have a Rails app that stores time values, and I have set a time zone in config/application.rb.
This works correctly on datetime columns, but time columns show the time in UTC, not the specified time zone.
The time on these two examples are both stored as 20:50 (UTC) in the database, but when I show it in a view the time column shows as UTC and the datetime column is correctly shown in the chosen time zone.
time2: 2000-01-01 20:50:00 UTC
datetime2: 2012-02-09 21:50:00 +0100
Is this expected behavior? Shouldn't time types also use the configured time zone?
ActiveRecord uses TimeWithZone, where methods like localtime, utc, utc? may help you.
Yes, this is expected behavior. Rails (ActiveRecord) stores times in UTC, then coverts them to whatever time zone Time.zone is set to upon rendering in the view.
I give up this, Rails seems to totally ignore config.time_zone with time attributes and just uses it for datetime attributes for reasons I don't understand. And as it seems, not many others understand it as well.
I will change the time attributes to type string and parse it to a time object when I need to work with it as a time object. If this is fixed in a later Rails release I can always change back to using time attributes, but now I need to go on, this has been holding me back for days.
But thanks for trying to help :)

When is it appropriate to use Time#utc in Rails 2.1?

I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?
When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?
If you've set:
config.time_zone = 'UTC'
In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.
Then if you set Time.zone (in a before_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.
Just be careful with Time.now.
Also see:
http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/
http://errtheblog.com/posts/49-a-zoned-defense - you can use the JS here to detect zones
Hope that helps.
If your application has users in multiple time zones, you should always store your times in UTC (any timezone would work, but you should stick with the most common convention).
Let the user input in local time, but convert to UTC to store (and compare, and manipulate). Then, convert back from UTC to display in each users' local time zone.

Resources