By default Rails will display the time and date like this: 2014-03-10 10:25:41 +0700. So how if we want to customize format of time and date? In Ruby on Rails we can use strftime() method to format the time and date in order to make it more readable. Example: March 10, 2014.

It’s really simple to use strftime() method, all we need to is give the object the time and date format, i.g.:

current_time =  
current_time.strftime("%B %d, %Y")  
=> "March 13, 2014"

Where %b %d, %Y is the format you want. Here’s some of the commonly used formats:

%a - Short weekday name (“Sun”)

%A - Full weekday name (“Sunday”)

%b - Short month name (“Jan”)

%B - Full month name (“January”)

%m - Month of the year (01..12)

%c - Preferred local date and time ("Thu Mar 13 11:30:15 2014")

%d - Day of the month (01..31)

%H - Hour of the day, 24-hour clock (00..23)

%I - Hour of the day, 12-hour clock (01..12)

%M - Minute of the hour (00..59)

%p - Meridian indicator upcase (“AM” or “PM”)

%P - Meridian indicator downcase (“am” or “pm”)

%S - Second of the minute (00..60)

%x - Simple date ("03/13/14")

%X - Simple time ("13:20:16")

%y - Year without a century (00..99)

%Y - Year with century ("2014")

You can also use rails default rails created_at field like this:

@post.created_at.strftime("Posted on %B %d, %Y at %H:%M")
=> "Posted on March 13, 2014 at 13:45"

Written by Irfan Fadilah – Author at 41studio

Read more at the source