Question

I am dynamically updating the underlying model by passing the parameters from the posted form to the model like this:

@model.assign_attributes(params[:model])

I have a date coming in along with the rest of the post data in the format mm/dd/yyyy. Ruby appears to be parsing this date as if it is in the format dd/mm/yyyy, as far as I can tell. So, when I enter a date of 4/15/2014, for instance, the model fails to save because the month 15 does not exist (I assume, in reality I am just told that the date field is required).

How can I configure Ruby to parse my dates as mm/dd/yyyy?

Was it helpful?

Solution

Use the strptime method for date and supply the format.

Date.strptime("4/15/2014","%m/%d/%Y")
#=> #<Date: 2014-04-15 ((2456763j,0s,0n),+0s,2299161j)>

You will probably have to specify a call back like before_update if you want the conversion to happen in the model. e.g.

class YourModel < ActiveRecord::Base


  before_update :format_date


  def format_date
    date_field = Date.strptime(date_field,'%m/%d/%Y')
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top