How to get the day of the month in Ruby

Overview

We can get the day of the month in Ruby using the day method of the Time object. We can call it on object anytime.

Syntax

t_o.day
Syntax to get day of the Month in Ruby

Parameter

t_o: The Time object to get the day of the month.

Return value

The day method returns the day of the month, that is, from 1st to 31st.

Code

Let’s take a look at the code:

# create Time Objects
t1 = Time.now
t2 = Time.new(1998)
t3 = Time.new(2003, 03, 29)
# get the date
a = t1.day
b = t2.day
c = t3.day
# print results
puts a
puts b
puts c

Explanation

  • Line 2: We create a time object using the Time.now which returns the current system time.
  • Line 3: We use the Time.new to create a Time object whose time is in 1998.
  • Line 4: We use the same Time.new() method to create another Time object.
  • Lines 7 to 9: We call the day method on the time objects we created.
  • Lines 12 to 14: We print the results.

Free Resources