3

I have a datepicker that I want to display in MM/DD/YYYY. However I'm using a mysql db which wants YYYY-MM-DD. As it stands right now its saving but the day and month are being reversed.

Right now I have an initalizer, date_time_formats.rb which has:

Date::DATE_FORMATS[:default] = '%m/%d/%Y'

Also in my datepicker jscript I have the correct format which I want to display:

$(this).datepicker({"format": "mm/dd/yyyy", "weekStart": 0, "autoclose": true, "startDate":new Date()});

I've tried things like this:

 Date.strptime(params[:location], "%d/%m/%Y")

But I get a HashWithIndifferentAccess error.

How can I reformat the date in the params hash prior to assigning to an instance of the model? The reason being it seems to get rejected from the model if the date would be invalid (ex. April 4, 2013 is fine, but April 20, 2013 is not because there is no 20th month). I'm a big time rails novice so maybe I'm wrong but thats how it appears to be working. Thanks!

3 Answers 3

5

try the american_date gem located here: https://github.com/jeremyevans/ruby-american_date

Sign up to request clarification or add additional context in comments.

Comments

1

Look up the strftime method of the various date classes. The incantation you want is Time.local(params[:location]).strftime('%m/%d/%Y'), hope that helps!

Comments

0

A quick way to sanitize the date to the correct format is to grab it in the controller before it gets saved and use strftime to correct the format. For example:

@model = Model.new(model_params)
@model.date_you_want = @model.date_you_want.strftime('%Y/%d/%m')
@model.save

This saves the date in the correct format. (I'm also using datepicker-boostrap gem)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.