Formatting date in Rails

December 30, 2009

The thing with which we deal everyday in our programming life is “Date”. This small, delicate stuff needs to be displayed in different formats in different places! In Rails there are many useful helpers to format date. Hence I am jolting down some so that I can take look quickly if I need one of them to use. You can take a look at it, too.

I have used strftime function of ActiveSupport class.

current_time = #today is 30 December, 2009
current_time.strftime("%m-%d-%y") # "12-30-09"
current_time.strftime("%b %d, %Y %I:%M%p") # "Dec 30, 2009 10:23PM"
current_time.strftime("%A %d, %B %Y") # "Wednesday 30, December 2009"
current_time.strftime("%A, %d %B %Y %I:%M%p") # "Wednesday, 30 December 2009 10:33PM"
current_time.strftime("%Y-%m-%d %H:%M:%S") # "2009-12-30 22:33:55"
current_time.strftime("%b %d, %Y") #=> "Dec 30, 2009"

By this time you may have understood the meaning of this format. Here is the explanation:

%Y – 2009 – Year with century

%y – 09 – Year without century

%B – January – Full month name

%b – Jan – Short month name

%m – 12 – Month number

%A- Wednesday-Full weekday name

%a- Wed-Short weekday name

%H –22 – Hour

%M –33 – Minute

%S –55 – Second

%p – AM or PM

Contributor: Fuad Bin Omar, COO, Nascenia

2 Comments. Leave new

Nice series of posts Fuad.

I will add something to your post here. you can use Date::DATE_FORMATS, DateTime::DATE_FORMATS, Time::DATE_FORMATS to see all preset formats. These are often handy!



How can I make the date and time use a certain time zone. The database uses UTC and would like to change it so that I can track the export time of an XML.

current_time =
XML ={
:@time => current_time.strftime(“%H%M%S”),
:@date => current_time.strftime(“%Y%m%d”)


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.