Time in Crystal

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

require "time"

def p(value)
  puts value
end

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

# You can build a Time struct by providing the
# year, month, day, etc. Times are always associated
# with a Location, i.e. time zone.
then = Time.utc(2009, 11, 17, 20, 34, 58, nanosecond: 651387237)
p then

# You can extract the various components of the time
# value as expected.
p then.year
p then.month
p then.day
p then.hour
p then.minute
p then.second
p then.nanosecond
p then.location

# The Monday-Sunday day of week is also available.
p then.day_of_week

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

# The - operator returns a Time::Span representing
# the interval between two times.
diff = now - then
p diff

# We can compute the length of the duration in
# various units.
p diff.total_hours
p diff.total_minutes
p diff.total_seconds
p diff.total_nanoseconds

# You can use + to advance a time by a given
# duration, or with a - to move backwards by a
# duration.
p then + diff
p then - diff

When you run this program, you’ll see output similar to the following:

2023-06-07 12:34:56.789012 UTC
2009-11-17 20:34:58.651387237 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
118270h0m0s
118270.0
7096200.0
425772000.0
425772000000000000
2023-06-07 12:34:58.651387237 UTC
1996-04-30 04:34:58.651387237 UTC

Note that the exact output will vary based on the current time when you run the program.

In Crystal, the Time struct is used to represent a moment in time. It provides methods for creating, manipulating, and formatting times. The Time::Span struct represents a duration of time.

Crystal’s Time API is quite similar to other languages, making it easy to work with dates and times in your programs.

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