Reputation: 96484
I can get my content_date
to show in mm/dd/yyyy format and I can save it correctly.
If I have a validation error in other data the form redisplays the date the desired way which is mm/dd/yyyy
I can also edit a record and see the date in format mm/dd/yy
The problem I have is that editing the record flips the month and year so that
08/02/2012
becomes
02/08/2012
and
08/19/2012
doesn't work at all.
Ironically If I record the record twice in a row and the day is not more than 12 it flips back to the original value
View:
= f.text_field :content_date, id: 'datepicker', size: 10
I got new and create to work with (links
controller)
def new
@link = Link.new
@link.content_date=Time.new().strftime("%m/%d/%Y")
...
def edit
@link = Link.find(params[:id])
@link.content_date=Time.new().strftime("%m/%d/%Y") if @link.content_date.nil?
def create
@link = Link.new(link_params)
if @link.content_date.nil?
@link.content_date = Time.new().strftime("%Y/%m/%d")
else
@link.content_date = @link.content_date.strftime("%Y/%m/%d")
end
but update
(rails 4.0.2
) is now just
def update
redirect_to Link.find(params[:id]).tap { |link|
link.update!(link_params)
}
end
and I can't figure out how to change the :content_date
in the update the way I did in the create
fyi I have the american_date
gem in my Gemfile
but it doesn't help (and doesn't help if I remove it either).
I don't currently have any date initializer in config/initializers/
js date picker:
$ cat app/assets/javascripts/date-picker.js
$(function() {
$( "#datepicker" ).datepicker();
});
$(function(){
var dateInput = $("#datepicker");
var format = 'yy-mm-dd';
dateInput.datepicker({dateFormat: format});
dateInput.datepicker('setDate', $.datepicker.parseDate(format, dateInput.val()));
});
Upvotes: 3
Views: 2146
Reputation: 96484
I changed
/app/assets/javascripts/datepicker.js
changing
var format = 'yy-mm-dd';
to
var format = 'mm/dd/yyyy';
Then I added a file config/inititlaizers/date-format.js
, with
# Date
# ----------------------------
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
# DateTime
# ----------------------------
DateTime::DATE_FORMATS[:default] = "%m/%d/%Y"
# Time
# ----------------------------
Time::DATE_FORMATS[:default] = "%m/%d/%Y %H:%M:%S"
This helped in all the displays and input fields and date-picker but the date still flipped.
Finally (this bit fixes the date flipping part), I changed my controller to be:
def update
r = Link.find(params[:id])
r.tap { |link|
link.update!(link_params)
}
r.update!(:content_date => link_params[:content_date].to_date.strftime("%Y-%d-%m"))
redirect_to r
end
Upvotes: 1