Using this quick guide, we will look at how to work with the date class in Ruby.
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:
Once imported, we can get the current date by creating an object to denote the current day.
cur_date = Date.today
Running the above code should return the current date.
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:
born_when = Date.today - 18250
In this case, we convert 50 years to days and subtract from the current date, giving us the birth year.
We can also add values to the current date object as:
born_when = Date.today + 30
This adds 30 days from the current date.
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:
time = Time.now
The time class also allows you to pass Epoch time and convert to human readable time format.
time = Time.at(1627882040)
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?
time = Time.now
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.