Skip to content

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

View the snippets archive ››

No comments have been left

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com