简体   繁体   中英

Rails to_json uses different DATE_FORMATS that .to_s

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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