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

List of sublime text shortcuts, tips and tricks

I started using sublime text over the past couple months (RIP textmate) and it’s been awesome so far. I wanted to create a short list of the shortcuts, tips and tricks that I’ve found most useful: Files cmd+p — Go to Anything cmd+ctrl+p... Continue →