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

Comments left...

  • Nice post – I presume you mean “create_at” though?

    Phil at 20 May 09 at 13:29

Got something to say?