Usually I have datetime fields in my webapp that are stored in the postgresql database as UTC time by Rails. When I go to display those dates and times on a webpage, they display in the local time because I have something similar to the following code:
before_filter :set_time_zone
def set_time_zone
Time.zone = "Pacific Time (US & Canada)"
end
Works great, except now I need to convert some of those datetime
fields to date
fields in the database (it's important). For example, I might have a log of dates students started:
Log.create(at: began_at, student_id: student_id)
began_at
is a datetime
field. It doesn't matter that I've set the Time.zone correctly, the at
field is a date
and it will be stored in postgresql as potentially the 1 day ahead or behind local time. When I go to display that date, it doesn't get converted to local time, which makes sense... if I haven't stored the time, how does Ruby/Rails know which day it was locally?
What I need is for the local date to be stored. So I need to convert began_at
to local time before assigning it to at
. What's the proper way to do this in a controller in Rails?
I'm using latest stable Rails (3.2.9 right now)