Formatting DateTimes in Ruby


Ruby has a highly customizable method for working with dates and times, strftime(remember it as "string format time").This method takes a directive and produces a formatted output. This makes it incredibly easy to format both dates and times in Ruby. First, let's create a new time object to work with:

>> now = Time.now()
2017-06-27 12:06:50 -0400

By calling time.now() ruby returns the current time, which is referenced by the 'now' variable. The time is provided as the year - month - day - hour. Time now() also has an alias of Time new(). Below is the comprehensive list of directives for the strftime method.

Directive Result
%D 06/16/1999
%b. %d, %Y Jan. 04, 2017
%I:%M: :p 05:45 AM
%a The abbreviated weekday name ("Sun")
%A The full weekday name ("Sunday")
%b The abbreviated month name ("Jan")
%B The full month name ("January")
%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 Month of the year (01..12)
%M Minute of the hour (00..59)
%p Meridian indicator ("AM" or "PM")
%x (alias %D) Date (%m/%d/%y)
%X (alias %T) 24-hour time (%H:%M:%S)
%R 24-hour time (%H:%M)
%r 12-hour time (%I:%M:%S %p)
%y Year without century (00..99)
%Y Year with century

The method should be called on a time object, for example, the 'now' variable we previously created. The syntax for the method is, .strftime('%x') where '%x' is the desired directive.

>> now.strftime('%D')
"06/27/17"

>> now.strftime('%B %d')
"June 27"

>> now.strftime('%I:%M %p')
"12:06 PM"

Being able to format the time object in so many different ways makes it very easy to create reusable code snippets. One place where this would come in handy is creating messages for users like, "Your last login was June 27th".

results matching ""

    No results matching ""