Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Time#<=>

time <=> other_time → -1, 0, +1, or nil

Compares time with other_time.

-1, 0, +1 or nil depending on whether time is less than, equal to, or greater than other_time.

nil is returned if the two values are incomparable.

Example
t = Time.now       #=> 2007-11-19 08:12:12 -0600
t2 = t + 2592000   #=> 2007-12-19 08:12:12 -0600
t <=> t2           #=> -1
t2 <=> t           #=> 1

t = Time.now       #=> 2007-11-19 08:13:38 -0600
t2 = t + 0.1       #=> 2007-11-19 08:13:38 -0600
t.nsec             #=> 98222999
t2.nsec            #=> 198222999
t <=> t2           #=> -1
t2 <=> t           #=> 1
t <=> t            #=> 0
See also #- #asctime #+ #as_json also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1