Time Formatting Parsing in Ruby

Ruby 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.strftime('%Y-%m-%dT%H:%M:%S%:z')

# Time parsing uses the same layout values as strftime.
t1 = Time.parse("2012-11-01T22:08:41+00:00")
puts t1

# strftime and parse use example-based layouts. Usually
# you'll use a constant from Time for these layouts, but
# you can also supply custom layouts.

puts t.strftime("%I:%M%p")
puts t.strftime("%a %b %e %H:%M:%S %Y")
puts t.strftime("%Y-%m-%dT%H:%M:%S.%N%:z")
form = "%I %M %p"
t2 = Time.strptime("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 format("%d-%02d-%02dT%02d:%02d:%02d-00:00",
  t.year, t.month, t.day,
  t.hour, t.minute, t.second)

# Parse will raise an ArgumentError on malformed input
# explaining the parsing problem.
begin
  Time.strptime("8:41PM", "%a %b %e %H:%M:%S %Y")
rescue ArgumentError => e
  puts e.message
end

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

2023-05-15T10:30:45+01:00
2012-11-01 22:08:41 +0000
10:30AM
Mon May 15 10:30:45 2023
2023-05-15T10:30:45.123456789+01:00
2000-01-01 20:41:00 +0000
2023-05-15T10:30:45-00:00
invalid strptime format - `%a %b %e %H:%M:%S %Y'

In Ruby, we use the Time class for working with dates and times. The strftime method is used for formatting times, while parse and strptime are used for parsing strings into Time objects.

Ruby’s time formatting is more flexible than some other languages, as it doesn’t require a specific reference time. Instead, it uses format specifiers like %Y for year, %m for month, etc.

For parsing, Ruby provides both Time.parse, which can handle many common formats automatically, and Time.strptime, which allows you to specify the exact format of the input string.

When parsing fails, Ruby raises an ArgumentError with a message explaining the problem, rather than returning an error value.