How to get time in seconds in Ruby

Overview

The seconds of a Time object in Ruby are within the range 0–60. We can use the sec method in Ruby to get the seconds of a Time object.

Syntax

t_o.sec
Get seconds of a Time object in Ruby

Parameters

The sec method takes no parameters. It is only invoked by the Time object, which in this case is t_o.

Return value

An integer value is returned that is within the range 0–60.

Example

# create time objects
t1 = Time.now # current time
t2 = Time.at(946702800)
t3 = Time.new(2002, 10, 31, 2, 2, 2)
# get the minutes
# and print results
puts t1.sec
puts t2.sec
puts t3.sec
puts "#{t3.to_a}"

Explanation

  • Line 2: We create a Time object that has the current time value.
  • Line 3: We pass in a number of seconds to the Time.at() method. This creates a Time object that corresponds to the seconds that we pass to it since the Unix Epoch.
  • Line 4: We create a time object using the Time.new(). We pass the year, month, day of the month, hour of the day, minutes of the day and finally the seconds of the minute.
  • Line 8–10: We call the sec method on the Time objects we created and print the results.
  • Line 12: Prints the t3 in the array format.

Free Resources