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
\"March 20, 2011\"
instead of
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"},
Time.now().strftime("%b %d, %Y)
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
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.
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