Rails to_json uses different DATE_FORMATS that .to_s

末鹿安然 提交于 2019-12-10 17:41:17

问题


With the following in my 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?


回答1:


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

See 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


来源:https://stackoverflow.com/questions/9280744/rails-to-json-uses-different-date-formats-that-to-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!