How to format dates in Ruby on Rails

Posted on 22 March 2006

To format dates in Ruby you can use the strftime directive that makes up part of the Ruby base library.

For example I used...

 <%= @website.created_on.strftime("%B %Y") %>

to output March 2006 for my latest portfolio entry. Where 'created_on' is the field in my database table 'websites'.

'created_on' is a so called 'magic field' in Ruby on Rails. Active Record will automatically create the timestamp in the database for you.

Another useful magic field is 'updated_on'. Whenever there's a change to that row the timestamp will be altered automatically.

Full list of strftime directives for formatting your output

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • Nice post - I presume you mean "create_at" though?

    Phil at 20 May 09 at 13:29

  • so so easy, thanks for the help man

    Al Doan at 20 Oct 11 at 23:07

  • Other solution is i18n http://stackoverflow.com/a/7372752

    jose at 10 May 12 at 16:12

Got something to say?