开发者

Format date time in find operation in Rails 3

开发者 https://www.devze.com 2023-02-18 04:13 出处:网络
I\'m looking for a way to format date time in find(:all) so that whe开发者_StackOverflown I render my results in JSON, the date time will look like

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

"March 20, 2011"

instead of

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

Does anyone have any suggestion? Thanks.


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


I would have used Date.parse(datestring) on the client to generate some usable content.


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


Off the top of my head, you could do something like:

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


That works (checked in Rails 3.1), put it into config/initializer/times_format.js. First two lines fix default time format (e.g. AR created_at). Third part is monkey patch for 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


Look you use jbuilder? and for example 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

in this example I am use method .to_formatted_s

 json.created_at textstring.created_at.to_formatted_s(:short

and i've got

[{"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"},
0

精彩评论

暂无评论...
验证码 换一张
取 消