简体   繁体   English

Rails控制台中的Rails日期

[英]Rails dates in rails console

My app create and save events with form into a mysql database. 我的应用程序创建事件并将事件保存到mysql数据库中。 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. 我是法国人,我的当地时间是格林尼治标准时间+ 200,并且Time.now使用本地时间机器。 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 但是在Rails控制台中我遇到了一个问题,例如,如果我在2016-09-12 18:30:00创建一个事件,当我运行时

Event.all 

in rails console i see : 在Rails控制台中,我看到:

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

i have 2 hour lag, but when i do 我有2小时的延迟,但是当我这样做时

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 : 我看到mysql日志,并且我的请求插入了正确的日期:

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 / application.rb的 #1内容

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. Rails始终将默认时间设置为UTC,因此它将数据库中的所有记录保存到该默认时区。 But you already changed the application.rb to Paris so the console show the correct time. 但是您已经将application.rb更改为Paris,以便控制台显示正确的时间。 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. 这样,Rails会在添加到数据库时跳过默认的time_zone来使用application.rb中的time_zone。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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