How to Convert Date Format in Ruby

09/20/2021

Contents

In this article, you will learn how to convert date format in Ruby.

Converting date formats

Ruby provides several methods to convert date formats. Here are some examples:

Using strftime method

The strftime method allows you to convert a Date or Time object to a specific format. You can use the format string to specify the format you want. Here’s an example:

date = Date.today
puts date.strftime("%d/%m/%Y")

This will output the current date in the format “dd/mm/yyyy”.

Using Date.strptime method

The strptime method allows you to convert a date string to a Date object. You can use the format string to specify the format of the date string. Here’s an example:

date_string = "2020-01-01"
date = Date.strptime(date_string, "%Y-%m-%d")
puts date.strftime("%d/%m/%Y")

This will output the date string in the format “dd/mm/yyyy”.

Using Date.parse method

The parse method allows you to convert a date string to a Date object. It can parse various formats of date strings. Here’s an example:

date_string = "01-01-2020"
date = Date.parse(date_string)
puts date.strftime("%d/%m/%Y")

This will output the date string in the format “dd/mm/yyyy”.

Using the strftime method with Time objects

You can also use the strftime method to format Time objects in Ruby. Here’s an example:

time = Time.now
puts time.strftime("%Y-%m-%d %H:%M:%S")

This will output the current date and time in the format “yyyy-mm-dd hh:mm:ss”.

Formatting options for strftime

The format string passed to strftime can contain various formatting options to control how the date or time is formatted. Some common options include:

  • %d: day of the month (01-31)
  • %m: month (01-12)
  • %Y: year (four digits)
  • %y: year (two digits)
  • %H: hour (00-23)
  • %M: minute (00-59)
  • %S: second (00-59)
  • %p: AM or PM
  • %a: abbreviated weekday name (Sun, Mon, Tue, etc.)
  • %A: full weekday name (Sunday, Monday, Tuesday, etc.)
  • %b: abbreviated month name (Jan, Feb, Mar, etc.)
  • %B: full month name (January, February, March, etc.)

Converting between Time and Date objects

You can convert between Time and Date objects in Ruby using the to_time and to_date methods. For example:

date = Date.today
time = date.to_time

This will convert the Date object to a Time object with the same date and a time of midnight.

time = Time.now
date = time.to_date

This will convert the Time object to a Date object with the same date but no time information.