How to add date/time created to your ruby on rails application

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

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 “created_at”. 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 “created_at” 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.

Enjoy!

 
0
Kudos
 
0
Kudos

Now read this

Using google maps to build a flight log

DEMO HERE # Airplanes and the idea of flight fascinated me as a young boy. I remember the anticipation of traveling to far away places with my family and could not wait to sit down in my blastoff seat and buckle up. One of my favourite... Continue →