Formatting dates is a common task when working with applications that need to display dates or store them in a specific format. In this blog post, we will explore various ways to format dates in Ruby using the built-in
Time classes and methods.
The most flexible way to format a date in Ruby is to use the strftime method, available for both
Time objects. The strftime method allows you to specify a format string containing placeholders for various date and time components, which will be replaced by their corresponding values.
Here’s an example of using strftime to format a date:
date = Date.new(2022, 12, 31) formatted_date = date.strftime("%m/%d/%Y") puts formatted_date # Output: 12/31/2022
In the example above, we’ve used the strftime method with the format string
"%m/%d/%Y" to display the date in a common US date format. You can customize the format string to include any combination of placeholders, which are specified using a percentage symbol followed by a letter.
Some common placeholders include:
%Y– year with century (e.g., 2022)
%y– year without century (e.g., 22)
%m– month (01-12)
%d– day of the month (01-31)
%H– hour (00-23)
%M– minute (00-59)
%S– second (00-60)
Using to_s and other built-in formatting methods
In addition to strftime, Ruby provides several built-in methods for commonly used date formats. For example, the to_s method, when called on a
Date object, returns the date in the format
Here’s an example:
date = Date.new(2022, 12, 31) formatted_date = date.to_s puts formatted_date # Output: 2022-12-31
Time class also provides methods like ctime and asctime to return a formatted string representing the date and time.
time = Time.new(2022, 12, 31, 12, 34, 56) formatted_time = time.ctime puts formatted_time # Output: Fri Dec 31 12:34:56 2022
In this blog post, we’ve explored how to format dates in Ruby using the strftime method and other built-in methods such as to_s and ctime. By utilizing these methods, you can easily display dates and times in any desired format to meet the needs of your application.