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 objectst1 = Time.now # current timet2 = Time.at(946702800)t3 = Time.new(2002, 10, 31, 2, 2, 2)# get the minutes# and print resultsputs t1.secputs t2.secputs t3.secputs "#{t3.to_a}"
Explanation
- Line 2: We create a
Timeobject that has the current time value. - Line 3: We pass in a number of seconds to the
Time.at()method. This creates aTimeobject 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
secmethod on theTimeobjects we created and print the results. - Line 12: Prints the
t3in the array format.