How do I change the format ActiveRecord expects when parsing dates from a text field in a form?

前端 未结 5 1675
孤独总比滥情好
孤独总比滥情好 2021-01-04 02:37

The problem

  1. I have a Ruby on Rails model with a Date attribute.
  2. In the form for this model, I am using a single text field with a JQuery datepicker
5条回答
  •  礼貌的吻别
    2021-01-04 02:52

    I just add the following monkey patch to config/time_formats.rb

    class Date
      class << self
        alias :euro_parse :_parse
        def _parse(str,comp=false)
          str = str.to_s.strip
          if str == ''
            {}
          elsif str =~ /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2,4})/
            year,month,day = $3.to_i,$1,$2
            date,*rest = str.split(' ')
            year += (year < 35 ? 2000 : 1900) if year < 100
            euro_parse("#{year}-#{month}-#{day} #{rest.join(' ')}",comp)
          else
            euro_parse(str,comp)
          end  
        end
      end
    end
    

提交回复
热议问题