30 December 2009

Formatting date in Rails

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 = Time.now #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

1 comment:

Unknown said...

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!