Set date format in ruby model (sinatra/datamapper)
I have a ruby model that contains a date attribue which I'd like to be able to pass in as a parameter in the format dd/MM/yyyy.
However, my sqlite3 db stores the data in yyyy-MM-dd format so when a date like 20/10/2010 gets passed in, it will not be read to the database.
I am using the Sinatra framework and using haml for the markup creation.
Do I need to write a helper that t开发者_JS百科akes the date string and converts it to the correct format for the db? Or can I set a format type on the models attribute?
Thanks.
You shouldn't need to worry about the database's internal representation of the date; DataMapper is there to do that for you. You just need to make sure you are passing it a valid Date
object.
Check out http://ruby-doc.org/core/classes/Date.html for methods available to the Date
class. For your example:
require 'date'
mydate = '20/10/2010'
mydate_obj = Date::strptime(mydate, '%d/%m/%Y')
puts "#{mydate_obj}" # prints 2010-10-20
I don't know if this can help, some time ago I had the same problem: I was using Rack::Utils.escape_html(params[:datetime])
to escape html on user input and if I typed a date in a form field like this "25/02/2013" it would be sent to the DataMapper model like this: 16/02/2013
(with escaped html codes) so it was saving it the wrong way (day ended up being the hour or something similar).
Maybe you are also using "escape_html" method in an awkward way?
精彩评论