Time in Ruby

Ruby offers extensive support for times and durations; here are some examples.

require 'time'

# We'll start by getting the current time.
now = Time.now
puts now

# You can build a Time object by providing the
# year, month, day, etc. Times are always associated
# with a time zone.
then = Time.utc(2009, 11, 17, 20, 34, 58, 651387)
puts then

# You can extract the various components of the time
# value as expected.
puts then.year
puts then.month
puts then.day
puts then.hour
puts then.min
puts then.sec
puts then.nsec
puts then.zone

# The Monday-Sunday day of the week is also available.
puts then.strftime("%A")

# These methods compare two times, testing if the
# first occurs before, after, or at the same time
# as the second, respectively.
puts then < now
puts then > now
puts then == now

# The '-' operator returns a Float representing
# the interval between two times in seconds.
diff = now - then
puts diff

# We can compute the length of the duration in
# various units.
puts diff / 3600 # hours
puts diff / 60   # minutes
puts diff        # seconds
puts diff * 1_000_000_000 # nanoseconds

# You can use '+' to advance a time by a given
# number of seconds, or with a '-' to move backwards.
puts then + diff
puts then - diff

To run the program, save it as time_example.rb and use ruby:

$ ruby time_example.rb
2023-05-31 10:15:30 +0000
2009-11-17 20:34:58 UTC
2009
11
17
20
34
58
651387000
UTC
Tuesday
true
false
false
425913932.3486781
118309.42565241059
7098565.539144636
425913932.3486781
425913932348678100
2023-05-31 10:15:30 UTC
1996-05-05 06:54:25 UTC

Ruby’s Time class provides similar functionality to Go’s time package. The main differences are:

  1. Ruby uses method calls instead of separate functions (e.g., time.Now() in Go becomes Time.now in Ruby).
  2. Ruby’s Time objects are mutable, unlike Go’s time.Time structs.
  3. Ruby represents durations as simple Float values (seconds), while Go has a separate Duration type.
  4. Ruby’s time arithmetic is done with standard + and - operators, while Go uses methods like Add and Sub.

Despite these differences, you can achieve similar time-related operations in Ruby as you can in Go.

Next, we’ll look at the related idea of time relative to the Unix epoch.