Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
time
communitycreator

How to get the hour of the day of a time object in Ruby

okwudili onyejiaku

Overview

The hour method returns the hour of the day when called on a time object in Ruby. The hour of the day is from 0-23 in Ruby time.

Syntax

t_o.hour
Syntax to get hour of time object of day in Ruby

Parameters

t_o: This is the time object whose hour we are getting.

Return value

An integer value is returned that is within the range 0-23.

Code example

# create time objects
t1 = Time.now # current time
t2 = Time.new(946702800)
t3 = Time.new(2002, 10, 31, 2, 2, 2)

# get the minutes
# and print results
puts t1.hour
puts t2.hour
puts t3.hour
Get the hour of a time object in Ruby

Explanation

  • Line 2: We create a time object that has a time value of current time.
  • Lines 3 and 4: We create time objects using the Time.new() method.
  • Lines 8-10: We call the hour method on the time objects we created and print the results.

RELATED TAGS

ruby
time
communitycreator
RELATED COURSES

View all Courses

Keep Exploring