简体   繁体   English

保存到数据库的不同日期 - 时区错误

[英]Different date saved to database - wrong time zone

When I fetch a date from FullCalendar with Javascript I have the following values: 当我使用Javascript从FullCalendar获取日期时,我有以下值:

Fri Sep 13 2013 08:30:33 GMT-0400 (EDT)

After I save that date to database I see that in database there are different values: 将该日期保存到数据库后,我发现在数据库中有不同的值:

2013-09-13 12:00:00.000000

So, date is automatically converted to UTC and saved like that into database. 因此,date会自动转换为UTC并像这样保存到数据库中。 How to save the correct date into database? 如何将正确的日期保存到数据库中? I don't want to hardcode it :) 我不想硬编码:)

Thank you. 谢谢。

By default, the rails app timezone is UTC. 默认情况下,rails app时区为UTC。 Whenever the record is saved the date, datetime, time fields are saved with DB's timezone but when they are fetched back in models it is converted back to UTC. 每当保存记录时,日期,日期时间,时间字段都会与DB的时区一起保存,但是当它们在模型中被取回时,它将被转换回UTC。

So, in your case set your application timezone in application.rb like this 因此,在您的情况下,在application.rb中设置您的应用程序时区就像这样

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

Now, whenever the records are fetched from database it will always be converted to CST timezone irrespective of DBs timezone. 现在,无论何时从数据库中获取记录,它都将始终转换为CST时区,而与DBs时区无关。

Hope this will help. 希望这会有所帮助。

For that you need to define your time zone in your application.rb 为此,您需要在application.rb中定义您的时区

config.time_zone = 'YOUR-TIME-ZONE'
config.active_record.default_timezone = :local
config.active_record.time_zone_aware_attributes = false

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

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