Rails 日期与 json [英] rails dates with json
问题描述
我正在实施一个 Facebook 应用程序并使用 AJAX/JSON.
I am implementing a Facebook application and using AJAX/JSON.
然而,返回的 JSON 结构具有这种格式 2010-05-30T06:14:00Z
.
However the JSON structures that are returned have this format 2010-05-30T06:14:00Z
.
我正在控制器操作中调用 Game.all.to_json
.
I'm calling Game.all.to_json
in controller action.
如何将它们转换为正常的日期格式?
How can I convert them to a normal date format?
使用 fbjs 从服务器端还是客户端更容易实现?fbjs 有很多错误.
Is it easier to do it from the server side or the client side using fbjs? There are a lot of bugs with fbjs.
所以我更喜欢使用来自 Server side
的解决方案,使用 (Active Records
).就像在发送 JSON
结构之前转换数据一样.
So i would prefer using a solution from the Server side
using (Active Records
). Like converting the data before sending the JSON
structures.
推荐答案
我将自己的自定义格式添加到返回的 json 的方法是向 ActiveSupport TimeWithZone 类添加一个猴子补丁.
The way I added my own custom format to the json I was returning was to add a monkey patch to the ActiveSupport TimeWithZone class.
在 config/initializers 文件夹中添加一个文件,内容如下:
Add a file in the config/initializers folder with the following contents:
class ActiveSupport::TimeWithZone
def as_json(options = {})
strftime('%Y-%m-%d %H:%M:%S')
end
end
这篇关于Rails 日期与 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!