Jonathan Clark
Jonathan Clark

Reputation: 20538

How to set timezone before saving

I am building a Rails 3.2 web app and when I supply a date (as a string) to the object I saving the date that gets saved is one day before.

So if I supply 2014-06-18 the date that gets saved is 2014-06-17. This is extremely annoying. Updated_at are saved correctly.

This is my code:

report = Timereport.new
report.status = "stop"
report.hours = 0
report.created_at = params[:created_at]
report.save

How can I fix this?

Update

params[:created_at] 
=> 2014-06-18

Time.zone
 => #<ActiveSupport::TimeZone:0x007fd94fbcb170 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=nil>

'2014-06-18'.to_datetime
 => Wed, 18 Jun 2014 00:00:00 +0000 

Upvotes: 0

Views: 425

Answers (2)

nabinabou
nabinabou

Reputation: 161

What is in

params[:created_at]

What shows you

'2014-06-18'.to_datetime

in the console?

And sure, what is

Time.zone

this will helps you/us to see more.

Upvotes: 0

Chris Peters
Chris Peters

Reputation: 18090

I'd recommend not changing this. Rails saves all dates as UTC in your database so they can be localized later.

What you want to do instead is have ActiveRecord translate the dates to a time zone when reading them from the database.

You can do this globally in config/application.rb with the config.time_zone setting.

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'

You can also do this according to the user's time zone, but it sounds like you just want to take care of it globally.

Upvotes: 1

Related Questions