Rails to_json使用与.to_s不同的DATE_FORMATS [英] Rails to_json uses different DATE_FORMATS that .to_s

查看:54
本文介绍了Rails to_json使用与.to_s不同的DATE_FORMATS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails_defaults.rb中包含以下内容:

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'

以下结果为何不同:

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" 

更重要的是,我如何获得 to_json 使用%m /%d /%Y

And more importantly, how do I get to_json to use %m/%d/%Y?

推荐答案

因为日期的标准JSON格式为%Y-%m-%d ,除非您覆盖<$ c,否则无法更改它$ c> Date#as_json (不要这样做,否则您的应用程序将开始出现异常)。

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

请参见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

这篇关于Rails to_json使用与.to_s不同的DATE_FORMATS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆