问题
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