在Rails 3中查找操作中格式化日期时间

我正在寻找一种在find(:all)中格式化日期时间的方法,这样当我用JSON渲染结果时,日期时间看起来像

“2011年3月20日”

代替

“2011-03-20T04:57:50Z”

有没有人有任何建议? 谢谢。

好的,所以你想要很好地呈现JSON格式的结果。 不是在路上改变日期的格式,而是在出路时改变它。

class Post def formatted_created_at created_at.strftime("%b %d, %Y") end def as_json(args={}) super(:methods=>:formatted_created_at, :except=>:date) end end 

我会在客户端上使用Date.parse(datestring)来生成一些可用的内容。

 Time.now().strftime("%b %d, %Y) 

在我的头顶,你可以做类似的事情:

 @posts = Post.all @posts.all.each do |x| x.date = x.date.strftime("%b %d, %Y") end @posts.to_json 

这工作(在Rails 3.1中检查),将其放入config / initializer / times_format.js。 前两行修复默认时间格式(例如AR created_at)。 第三部分是JSON的猴子补丁。

 Date::DATE_FORMATS[:default] = "%Y-%m-%d" Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S" class ActiveSupport::TimeWithZone def as_json(options={}) strftime('%Y-%m-%d %H:%M:%S') end end 

看你用jbuilder? 例如index.json.jbuilder

 json.array!(@textstrings) do |textstring| json.extract! textstring, :id, :text json.created_at textstring.created_at.to_formatted_s(:short) json.url textstring_url(textstring, format: :json) end 

在这个例子中,我使用方法.to_formatted_s

  json.created_at textstring.created_at.to_formatted_s(:short 

而且我有

 [{"id":1,"text":"liveasda","created_at":"17 Nov 12:48","url":"http://localhost:5555/textstrings/1.json"},{"id":2,"text":"123","created_at":"17 Nov 14:26","url":"http://localhost:5555/textstrings/2.json"},