How to add date/time created to your Ruby on Rails application

  <h1><%= @article.title %></h1>
  Posted by:
  On<%= @article.created_at.strftime("%B %d %Y, %l:%M%P") %>
  <h4><%= @article.text %></h4>

After a good time spent searching how to do this online, I thought it would be helpful to write a blog post about it.

I am building a message board using rails and I wanted to add the date/time a post was created on the site. E.g. when a user creates a new post, the date and time that post was entered into the database should show on the page.

To do this we can use a rails built-in method called “createdat”. In the above example I have a snapshot of my codebase in the show.html.erb file. In order to show the date/time created I called the “createdat” method on an instance of my @article class which contains all of the posts for each user. However, this will output the date/time in a pretty ugly format: ‘2013–04–20 01:32:11 UTC’.

You can use the “strftime” method to show the date/time in a more readable format. The strftime formats can be found here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s