Different date saved to database - wrong time zone

2020-08-03 04:42发布

问题:

When I fetch a date from FullCalendar with Javascript I have the following values:

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. How to save the correct date into database? I don't want to hardcode it :)

Thank you.

回答1:

For that you need to define your time zone in your application.rb

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


回答2:

By default, the rails app timezone is 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.

So, in your case set your application timezone in application.rb like this

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.

Hope this will help.