Time Formatting Parsing in Crystal

Crystal supports time formatting and parsing via pattern-based layouts.

require "time"

# Here's a basic example of formatting a time
# according to RFC3339, using the corresponding layout
# constant.
t = Time.now
puts t.to_rfc3339

# Time parsing uses the same layout values as `to_s`.
t1 = Time.parse("2012-11-01T22:08:41+00:00", "%FT%T%:z")
puts t1

# `to_s` and `parse` use example-based layouts. Usually
# you'll use a constant from `Time::Format` for these layouts, but
# you can also supply custom layouts. Layouts must use the
# reference time `%Y-%m-%d %H:%M:%S` to show the
# pattern with which to format/parse a given time/string.

puts t.to_s("%I:%M%p")
puts t.to_s("%a %b %e %H:%M:%S %Y")
puts t.to_s("%Y-%m-%dT%H:%M:%S.%L%:z")

form = "%I %M %p"
t2 = Time.parse("8 41 PM", form)
puts t2

# For purely numeric representations you can also
# use standard string formatting with the extracted
# components of the time value.
puts "%d-%02d-%02dT%02d:%02d:%02d-00:00" % [
  t.year, t.month, t.day,
  t.hour, t.minute, t.second
]

# `parse` will raise an exception on malformed input
# explaining the parsing problem.
begin
  Time.parse("8:41PM", "%a %b %e %H:%M:%S %Y")
rescue ex
  puts ex
end

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

2023-05-15T12:34:56Z
2012-11-01 22:08:41 UTC
12:34PM
Mon May 15 12:34:56 2023
2023-05-15T12:34:56.789+00:00
0001-01-01 20:41:00 UTC
2023-05-15T12:34:56-00:00
Invalid time string: 8:41PM

Crystal’s Time class provides methods for formatting and parsing time. The to_s method is used for formatting, while parse is used for parsing.

Crystal uses strftime-style format specifiers (like %Y, %m, %d, etc.) instead of the example-based layouts used in some other languages. This makes it more similar to Ruby’s time formatting.

The Time::Format module provides constants for common time formats, similar to the RFC3339 constant used in the original example.

For parsing, Crystal’s Time.parse method takes two arguments: the time string and the format string. If the parsing fails, it raises an exception rather than returning an error value.

Crystal doesn’t have a direct equivalent to the reference time concept used in some other languages. Instead, it uses the standard strftime format specifiers to define custom layouts.

Remember that Crystal’s Time handling, while similar in many ways to other languages, has its own unique features and syntax. Always refer to the Crystal documentation for the most up-to-date and accurate information.