简体   繁体   中英

Rails dates in rails console

My app create and save events with form into a mysql database. I use something like that

event = Event.new .... start_date: Time.now ...

I'm french, my local time is GMT + 200, and Time.now use local Time machine. But in rails console i have a problem, for example if i create an event at 2016-09-12 18:30:00 when i run

Event.all 

in rails console i see :

#... <Event id: 5 ... start_date: 2016-09-12 16:30:00 ...

i have 2 hour lag, but when i do

e = Event.find 5
e.start_date

i have result

Mon, 12 Sep 2016 18:30:00 CEST +02:00

The good time. I see mysql log and my request insert the correct date :

INSERT INTO `events` ... 2016-09-12 18:30:00'

I precise my app works perfectly, i just want to understand that. Thanks

Edit #1 Content of my config/application.rb

config.active_record.default_timezone = :local
config.time_zone = 'Paris'

Rails defaults all times to UTC so it saves all records in the database to this default timezone. But you already changed the application.rb to Paris so the console show the correct time. But for the database it doesn't change a thing.

You can use:

event = Event.new .... start_date: Time.now.in_time_zone ...

This way Rails skips the default time_zone to use the time_zone in your application.rb when adding to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM