PaR*_*Nos 13 datetime ruby-on-rails-4
我正在使用rails生成API,其中一些响应包含日期.在我的数据库中,字段被设置为datetime字段,然后rails将变为ActiveSupport::TimeWithZone对象.当我回复日期时间的请求时,我希望得到类似的结果
2013-07-23T01:18:32Z
Run Code Online (Sandbox Code Playgroud)
但相反,我得到了
2013-07-23T01:18:32.000Z
Run Code Online (Sandbox Code Playgroud)
为什么最后还有额外.000的?现在,这正在打破我正在编写的客户端上的代码.显然我可以通过改变它期望的格式来修复客户端,但我想知道为什么rails首先会这样做,因为文档表明它不应该有.000那里.
如果要恢复为没有毫秒的格式,可以使用以下代码添加初始化程序:
class ActiveSupport::TimeWithZone
#Changing the as_json method to remove the milliseconds from TimeWithZone to_json result (just like in Rails 3)
def as_json(options = {})
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema
else
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
end
Run Code Online (Sandbox Code Playgroud)
对于来自谷歌的其他人.还有一个相关的问题有更多的最新答案为Rails 4.1+ 这里.
现在可以配置JSON时间编码的精度.根据Rails升级指南,您现在可以在初始化程序中添加以下行而不是猴子修补程序:
ActiveSupport::JSON::Encoding.time_precision = 3
Run Code Online (Sandbox Code Playgroud)
看起来这是 Rails 4 中的一个变化
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/time_with_zone.rb#L157
看来 API 文档需要更新:(