Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time.now & Created_at are different? Ruby on Rails

My site is deployed on heroku. Time.now will return today, but the created_at field of a record (created right now) will say its tomorrow. I assume this has to do with server time?

Is there a way to make sure they're the same? Best, Elliot


Update so I did this "heroku rake time:zones:us"

it gave me:

    * UTC -10:00 *
Hawaii

* UTC -09:00 *
Alaska

* UTC -08:00 *
Pacific Time (US & Canada)

* UTC -07:00 *
Arizona
Mountain Time (US & Canada)

* UTC -06:00 *
Central Time (US & Canada)

* UTC -05:00 *
Eastern Time (US & Canada)
Indiana (East)

however, when I set config.time_zone = 'UTC -05:00' in my environment, the app fails to start. any ideas?

like image 863
Elliot Avatar asked Mar 25 '10 00:03

Elliot


People also ask

What's the time is right now?

NIST. 04:02:04 P.M.


2 Answers

Rails always stores UTC time on the database; the created_at field by itself should be offset by exactly your timezone's variation relative to UTC.

Whenever you load a record in your application, the fields get converted to the timezone specified in environment.rb. It might have something like this:

config.time_zone = 'UTC'

For the time to be converted properly to your timezone, you might change this configuration setting to one matching your actual time zone. For instance:

config.time_zone = 'Central Time (US & Canada)'

To see available zones, issue "rake -D time" on your rails directory. This will give you instructions on how to get time zone names for use in configuration.

like image 64
Roadmaster Avatar answered Sep 16 '22 18:09

Roadmaster


To add onto Roadmaster's answer, I had a similar challenge: the normal Rails timestamps were stored based on UTC in the database, but I needed to query to find all records created today according to the local time zone.

The query looked like this:

completions.where("created_at BETWEEN ? AND ?", 
  Date.today, Date.today + 1.day).count >= 1

I fixed this by calling #to_time on the dates, as follows. This converted them into a timestamp having the proper time zone, and the correct records were fetched in the database, effectively making the query timezone-aware.

completions.where("created_at BETWEEN ? AND ?", 
  Date.today.to_time, Date.today.to_time + 1.day).count >= 1
like image 22
Topher Hunt Avatar answered Sep 16 '22 18:09

Topher Hunt