Anand
Anand

Reputation: 10400

Trouble with time attribute in Ruby on Rails

I am having this trouble in converting the exiting time string into a new Time object.

When I type this in console

t = Time.parse("8am")  
2010-12-06 08:00:00 +0530

it gives back 08:00 as result as seen above.

But when I store this value using

business.start_time = t
business.save(:validate => false)

it stores 02:30 in MySql db.

This happens only when I store via console. When the same data comes from forms, it stores correctly as 08:00 in MySQL table. Is there any problem here. The time zone is set different from the default utc. Please help. what should i do.

I have to parse through all the records in a table and take one string attribute and convert it into its equivalent Time class value and store it in another attribute in the same table. I am writing a rake task for it. But while storing, I get 02:30 instead 08:00 (for example).

Upvotes: 1

Views: 937

Answers (2)

aceofspades
aceofspades

Reputation: 7586

Be very careful with dates and MySQL. Datetime fields are stored as if they were strings in the db--so whatever Rails is sending in (check your log for the SQL) is what will be stored. I assume you're set to UTC in your environment.rb, so your Time object is being output in UTC as a string.

MySQL is poor (in my opinion) with respect to handling times in different zones and converting between zones.

I recommend you don't rush through your date handling. Always handle dates in your application and DB in UTC, and do any conversion to a specific timezone on a parsing (by specifying the timezone) or by formatting it in the view.

Upvotes: 2

David Sulc
David Sulc

Reputation: 25994

The time seems to be stored in UTC. Try setting the timezone correctly when starting your console session.

Upvotes: 0

Related Questions