在 Rails 3 中的查找操作中格式化日期时间 [英] Format date time in find operation in Rails 3

查看:14
本文介绍了在 Rails 3 中的查找操作中格式化日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 find(:all) 中格式化日期时间的方法,以便当我以 JSON 呈现结果时,日期时间看起来像

I'm looking for a way to format date time in find(:all) so that when I render my results in JSON, the date time will look like

2011 年 3 月 20 日"

"March 20, 2011"

代替

2011-03-20T04:57:50Z"

"2011-03-20T04:57:50Z"

有人有什么建议吗?谢谢.

Does anyone have any suggestion? Thanks.

推荐答案

好的,所以您希望以 JSON 格式很好地呈现结果.不要在输入时更改日期格式,而是在输出时更改它.

OK, so you want to render the results in JSON formatted nicely. Instead of changing the format of the date on the way in, change it on the way out.

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

这篇关于在 Rails 3 中的查找操作中格式化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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