Change format of created_at in Rails 3.1?

dannymcc picture dannymcc · Sep 10, 2011 · Viewed 34.2k times · Source

I am calling the date a record was created at in a basic app running Rails 3.1.

<%= @issue.created_at %>

The above outputs the following timestamp:

2011-09-10 14:44:24 UTC

What is the simplest way of altering the way this displays? I would like something like this:

10 Sept. 2011

and then somehow call it again with a different format:

14:44

so I can call it twice and merge the two together:

10 Sept. 2011
14:44

The reason I want to call it twice rather than create a helper to format a two line date/time is to allow me to call the date in some places and just the time in others.

Answer

spike picture spike · Sep 10, 2011

The simplest thing to do is to use the strftime function

# Day / Month / Year
@issue.created_at.strftime("%d %b. %Y")
# Hour:Min
@issue.created_at.strftime("%H:%M")

You could put those two calls in separate helpers if you find yourself doing it a lot.