How to Display the Current Date and Time in Ruby

09/18/2021

Contents

In this article, you will learn how to display the current date and time in Ruby.

How to display the current date and time

Using Time class

In Ruby, you can display the current date and time using the built-in Time class. Here’s an example:

current_time = Time.now
puts "The current date and time is: #{current_time}"

This will output something like:

The current date and time is: 2023-03-03 10:24:51 +0000

You can also format the output to display only the date or time if you prefer. Here are some examples:

# Display only the date
current_date = Time.now.strftime("%Y-%m-%d")
puts "Today's date is: #{current_date}"

# Display only the time
current_time = Time.now.strftime("%H:%M:%S")
puts "The current time is: #{current_time}"

This will output something like:

Today's date is: 2023-03-03
The current time is: 10:24:51

You can adjust the format string to display the date and time in different formats. The %Y, %m, %d, %H, %M, and %S are placeholders for year, month, day, hour, minute, and second respectively. For example, %Y-%m-%d %H:%M:%S would format the output like 2023-03-03 10:24:51.

 

There are other ways to display the current date and time in Ruby. Here are a few examples:

Using DateTime class

require 'date'

current_datetime = DateTime.now
puts "The current date and time is: #{current_datetime}"

This will output something like:

The current date and time is: 2023-03-03T10:29:14+00:00

Using strftime method with a specific format

current_time = Time.now.strftime("%A, %B %d %Y %H:%M:%S")
puts "The current date and time is: #{current_time}"

This will output something like:

The current date and time is: Thursday, March 03 2023 10:31:37

Using Time.now method directly inside a string

puts "The current date and time is: #{Time.now}"

This will output something like:

The current date and time is: 2023-03-03 10:33:54 +0000

All of these methods essentially do the same thing, which is to retrieve the current date and time and format it in a particular way. The method you choose to use will depend on your specific needs and preferences.