ActiveRecord date format

我与影子孤独终老i 提交于 2019-11-28 23:21:31

Rails' DateTime tries to detect the formatting automatically. It will detect the following formats: mm/dd/yy or dd-mm-yy or yyyy-mm-dd or yyyy/mm/dd. You could monkey-patch DateTime.parse, but I would rather move this issue to the View of your application.

I always recommend to use yyyy-mm-dd [hh:mm:ss] as a string representation for a date. Check the documentation of your DatePicker if it supports multiple date-formats.

The jQuery date-picker for example has this covered with dateFormat (for the data that is sent to the server, set this to yyyy-mm-dd) as well as altFormat (for the input the user sees, set this to dd/mm/yyyy).

Add a file called rails_defaults.rb to config\initializers directory; with following lines:

Date::DATE_FORMATS[:default] = '%d/%m/%Y'
Time::DATE_FORMATS[:default]= '%d/%m/%Y %H:%M:%S'

Restart the server and you are good to go.

class Date
  class << self
    def _parse_with_us_format(date, *args)
      if date =~ %r{^(\d+)/(\d+)/(\d+)$}
        _parse_without_us_format("#{$3.length == 2 ? "20#{$3}" : $3}-#{$1}-#{$2}", *args)
      else
        _parse_without_us_format(date, *args)
      end
    end
    alias_method_chain :_parse, :us_format
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!