Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

time
ruby
communitycreator

How to know the day name of a Time object in Ruby

okwudili onyejiaku

Overview

In Ruby, we have several similar methods to know the day name of a time object. The technique is the same for all: timeObject.dayName?. Here, the dayName can be any day of the week, for example, thursday, wednesday, monday, and so on.

Syntax

timeObject.dayName?

Parameters

timeObject: This is the Time object we want to check.

dayName: This is the method name. It could be any day of the week.

Return value

The value returned is a Boolean value. It can be true or false. true is returned if timeObject occurs on dayName. Otherwise, a false is returned.

Example

# create time objects
timeObjectOne = Time.now # current time
timeObjectTwo = Time.new(1995, 12, 21) # Thursday in 1990
timeObjectThree = Time.new(1990, 4, 1)   # Sunday in 1998
timeObjectFour = Time.new(1987, 12, 19) # Saturday December, 1987
timeObjectFive = Time.new(2022, 01, 21) # Friday January, 2022

# check day name
puts timeObjectOne.monday? 
puts timeObjectTwo.thursday?
puts timeObjectThree.sunday?
puts timeObjectFour.saturday?
puts timeObjectFive.wednesday?
Get the day of the week in Ruby

Explanation

Line 2–6: We create the following Time objects:

  • timeObjectOne
  • timeObjectTwo
  • timeObjectThree
  • timeObjectFour
  • timeObjectFive

Line 9–13: Some of the methods that we explained earlier are called on the Time objects we created. We print the results to the console.

RELATED TAGS

time
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring