Ruby

Ruby Get Current Date

Working and manipulating date values in Ruby is pretty straightforward because the language provides the date class and various methods to perform actions on date objects.

Using this quick guide, we will look at how to work with the date class in Ruby.

Basic Usage

The date class is part of the Ruby standard library that has a ton of other methods. To use it, we need to import by adding the following entry:

require 'date'

Once imported, we can get the current date by creating an object to denote the current day.

require 'date'
cur_date = Date.today
puts cur_date

Running the above code should return the current date.

2021-08-01

Once we get the current date, we can perform basic functions such as adding or subtracting the days.

For example, to find out when someone aged 50 years was born, we can do:

require 'date'
born_when = Date.today - 18250
puts born_when

In this case, we convert 50 years to days and subtract from the current date, giving us the birth year.

1971-08-14

We can also add values to the current date object as:

require 'date'
born_when = Date.today + 30
puts born_when

This adds 30 days from the current date.

2021-08-31

Ruby Time Class

A sister class to date is the Time class. The time class works similarly to date but offers the concept of date and time. It represents a specific point in time in years, months, days, hours, minutes, and seconds.

For example, to get the current date and time using the time class, you can do:

require 'time'
time = Time.now
puts time
2021-08-01 08:24:49

The time class also allows you to pass Epoch time and convert to human readable time format.

For example:

require 'time'
time = Time.at(1627882040)
puts time
2021-08-02 08:27:20

The above method will convert the passed epoch time to readable time format.

You can also query the time for the specific day. For example, to get if the current date is Monday?

require 'time'
time = Time.now
puts time
puts time.monday?
2021-08-02 08:38:04
true

Closing

This tutorial went over the basics of using the date and class functions to get the current date and time. Ruby provides more functionality for working with date and time, including formatting. Refer to the documentation to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list