How to set datetime format in Rails -
i using js calendar inserts string text field submission datetime value. not sure if matters using sqlite now.
i setting format follows (in 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 apparently validating date using different format.
for example, if set follows:
myobject.my_datetime = '06/30/2012 00:00' it ends null (the sql query generated activerecord sets null). if set day less or equal 12 date part ends correct (but generated sql query still shows string day before month, i.e. in above example sql query has string '30/06/2012 05:00:000000').
as can see seems adding 5 hours utc(?) though have config.time_zone set eastern time.
behavior same either console or via form submission.
any suggestions on missing?
update:
when follow jdoe's suggestion , this:
myobject.my_datetime = time.strptime('06/30/2012 08:00', '%m/%d/%y %h:%m')
the generated query looks correct (ignoring 4 hour difference):
update "myjoin_table" set "my_datetime" = '06/30/2012 04:00.000000' ..... and winds in database way.
but when reload object value in ar object initialized nil.
i guess i'll parse string piece piece in controller action , set parameters update_attributes manually. harder should be.
activerecord stores date/time in utc+00:00. if you're living in +5 zone, activerecord subtract 5 hours on assigning automatically. so, current time zone says how many hours has added/subtracted local time.
about parsing. did try following?
myobject.my_datetime = time.strptime('06/30/2012 00:00', '%m/%d/%y %h:%m') rails time/date settings made showing, not assignment. it's not brilliant idea strings user , assign them date/time attributes. you'd better use proper time objects in assignment instead of stings. strptime method raise argumenterror if user trying hacker. record.date_time='string' fails silently.
upd: usage example
p = product.first p.last_visited = time.strptime('06/30/2012 00:00', '%m/%d/%y %h:%m') p.save # leads update "products" set "last_visited" = '2012-06-29 21:00:00.000000' product.last_visited.localtime.strftime('%m/%d/%y %h:%m') # => "06/30/2012 00:00" as see, time stored , retrieved w/o problems.
upd 2: i18n
locate config/locales/en.yml. add following it:
en: time: formats: default: '%m/%d/%y %h:%m' to parse time use t(or translate) helper:
@time = time.strptime('06/30/2012 00:00', t('time.formats.default')) use l(or localize) helper show time in format:
= l @time
Comments
Post a Comment