Rails - how to show and store a date in our format?

I can show mine content_date

in mm / dd / yyyy format and I can save it correctly. If I have a validation error in other data, the form re-displays the date of the desired way, which is mm/dd/yyyy

I can also edit the entry and see the date in mm / dd / yy format

The problem is that editing the entry reverses 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 a record twice in a row, and the day is no more than 12, then it returns to its 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 :content_date

in update the way i did in creation

fyi I have a american_date

gem in mine Gemfile

, but it doesn't help (and doesn't help if I remove it).

I currently don't have a 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()));
});

      

+3


source to share


1 answer


I changed

/app/assets/javascripts/datepicker.js

      

changes

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 displays, input fields, and date picker, but the date was still flipping.

Finally (this bit captures the date flipping part), I changed my controller like this:

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

      

+1


source







All Articles