Ruby-on-rails ActiveRecord 日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2529990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:27:57  来源:igfitidea点击:

ActiveRecord date format

ruby-on-railsactiverecorddate-format

提问by Mongus Pong

I've run into a spot of bother with date formats in our Rails application.

我在 Rails 应用程序中遇到了日期格式的麻烦。

I have a date field in our view which I want to be formatted as dd/mm/yy. This is how the user will expect to enter their dates, and the datepicker control uses this format.

我的视图中有一个日期字段,我想将其格式化为dd/mm/yy。这是用户期望输入日期的方式,日期选择器控件使用这种格式。

However, Active Record seems to be expecting mm/dd/yy.

但是,Active Record 似乎期待mm/dd/yy

If I enter 01/03/2010, this gets put in as 03 January 2010.

如果我输入01/03/2010则会将其输入为03 January 2010

If I enter 25/03/2010, this gets put in a null.

如果我输入25/03/2010则会将其放入null

How do I get ActiveRecord to expect Her Majesties date format?

我如何让 ActiveRecord 期待女王陛下的日期格式?

回答by Marcel Hymanwerth

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

Rails 的 DateTime 尝试自动检测格式。它将检测以下格式:mm/dd/yyordd-mm-yyyyyy-mm-ddor yyyy/mm/dd。您可以使用 monkey-patch DateTime.parse,但我宁愿将此问题移至您的应用程序的视图

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.

我总是建议使用yyyy-mm-dd [hh:mm:ss]作为日期的字符串表示。如果它支持多种日期格式,请检查您的 DatePicker 的文档。

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).

例如,jQuery 日期选择器包含dateFormat(对于发送到服务器的数据,将其设置为yyyy-mm-dd)以及altFormat(对于用户看到的输入,将其设置为dd/mm/yyyy)。

回答by Harish Shetty

Add a file called rails_defaults.rbto config\initializersdirectory; with following lines:

添加一个名为rails_defaults.rbconfig\initializers目录; 有以下几行:

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.

重新启动服务器,您就可以开始了。

回答by grosser

class Date
  class << self
    def _parse_with_us_format(date, *args)
      if date =~ %r{^(\d+)/(\d+)/(\d+)$}
        _parse_without_us_format("#{.length == 2 ? "20#{}" : }-#{}-#{}", *args)
      else
        _parse_without_us_format(date, *args)
      end
    end
    alias_method_chain :_parse, :us_format
  end
end