Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change format of created_at in Rails 3.1?

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.

like image 628
dannymcc Avatar asked Sep 10 '11 15:09

dannymcc


2 Answers

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.

like image 176
spike Avatar answered Oct 11 '22 10:10

spike


I would use I18n. Take a look at some example http://guides.rubyonrails.org/i18n.html#adding-date-time-formats. It's a clean and flexible way of formatting dates and times.

like image 26
lucapette Avatar answered Oct 11 '22 10:10

lucapette