简体   繁体   English

Rails to_json使用与.to_s不同的DATE_FORMATS

[英]Rails to_json uses different DATE_FORMATS that .to_s

With the following in my rails_defaults.rb: 在我的rails_defaults.rb中包含以下内容:

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

Why do the following results differ: 为什么以下结果不同:

ruby-1.9.2-p180 :005 > MyModel.find(2).to_json(:only => :start_date)
 => "{\"start_date\":\"2012-02-03\"}" 

ruby-1.9.2-p180 :006 > MyModel.find(2).start_date.to_s
 => "02/03/2012" 

And more importantly, how do I get to_json to use %m/%d/%Y ? 更重要的是,如何获取to_json以使用%m/%d/%Y

Because the standard JSON format for a date is %Y-%m-%d and there's no way to change it unless you override Date#as_json (don't do so or your application will start misbehaving). 由于日期的标准JSON格式为%Y-%m-%d ,除非您覆盖Date#as_json ,否则无法更改它(请勿这样做,否则应用程序将开始出现异常)。

See https://github.com/rails/rails/blob/master/activesupport/lib/active_support/json/encoding.rb#L265-273 参见https://github.com/rails/rails/blob/master/activesupport/lib/active_support/json/encoding.rb#L265-273

class Date
  def as_json(options = nil) #:nodoc:
    if ActiveSupport.use_standard_json_time_format
      strftime("%Y-%m-%d")
    else
      strftime("%Y/%m/%d")
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM