I am using a js calendar that inserts a string into a text field for submission as a datetime value. Not sure if it matters but I am using SQLite for now.
I am setting the format as follows (in an initializer):
Time::DATE_FORMATS[:default] = '%m/%d/%Y %H:%M'
Time::DATE_FORMATS[:db] = '%m/%d/%Y %H:%M'
This isn’t working because Rails is apparently validating the date using a different format.
For example, if I set it as follows:
myobject.my_datetime = '06/30/2012 00:00'
it ends up null (the SQL query itself generated by ActiveRecord sets it to NULL). If I set it to a day less than or equal to 12 the date part ends up correct (but the generated SQL query still shows the string with the day before the month, i.e. in the above example the SQL query has the string as ’30/06/2012 05:00:000000′).
As you can see it also seems to be adding 5 hours for UTC(?) even though I have config.time_zone set to eastern time.
Behavior is the same either from console or via form submission.
Any suggestions on what I am missing?
UPDATE:
When I follow jdoe’s suggestion and do this:
myobject.my_datetime = Time.strptime(’06/30/2012 08:00′, ‘%m/%d/%Y %H:%M’)
The generated query now looks correct (ignoring the 4 hour difference):
UPDATE "myjoin_table" SET "my_datetime" = '06/30/2012 04:00.000000' .....
and it winds up in the database that way.
But when I reload the object the value in the AR object is initialized to nil.
I guess I’ll just parse the string piece by piece in my controller action and set the parameters to update_attributes manually. This is harder than it should be.
ActiveRecord stores date/time in UTC+00:00. If you’re living in the +5 zone, ActiveRecord will subtract 5 hours on assigning automatically. So, your current time zone just says how many hours has to be added/subtracted from your local time.
About parsing. Did you try the following?
Rails time/date settings are made for showing, not for assignment. It’s not a brilliant idea to get strings from a user and assign them to your date/time attributes. You’d better use proper time objects in assignment instead of stings. The
strptimemethod will raise theArgumentErrorif some user is trying to be a hacker. Yourrecord.date_time='string'fails silently.UPD: Usage Example
As you see, time is stored and retrieved w/o any problems.
UPD 2: I18n
Locate your
config/locales/en.yml. Add the following to it:To parse your time use
t(ortranslate) helper:Use
l(orlocalize) helper to show time in your format: