Time Formatting Parsing in Nim

import std/times
import std/strformat

proc main() =
  let p = echo

  # Here's a basic example of formatting a time
  # according to RFC3339, using the corresponding layout
  # constant.
  let t = now()
  p(t.format("yyyy-MM-dd'T'HH:mm:sszzz"))

  # Time parsing uses the same format string as `format`.
  let t1 = parse("2012-11-01T22:08:41+00:00", "yyyy-MM-dd'T'HH:mm:sszzz")
  p($t1)

  # `format` and `parse` use format strings. Usually
  # you'll use a predefined format string, but you can
  # also supply custom formats. Formats must use the
  # reference time components to show the pattern with
  # which to format/parse a given time/string.

  p(t.format("h:mmtt"))
  p(t.format("ddd MMM d HH:mm:ss yyyy"))
  p(t.format("yyyy-MM-dd'T'HH:mm:ss.ffffff'-07:00'"))
  let form = "h mm tt"
  let t2 = parse("8 41 PM", form)
  p($t2)

  # For purely numeric representations you can also
  # use standard string formatting with the extracted
  # components of the time value.
  echo fmt"{t.year:d}-{t.month:02d}-{t.monthday:02d}T{t.hour:02d}:{t.minute:02d}:{t.second:02d}-00:00"

  # `parse` will raise an exception on malformed input
  # explaining the parsing problem.
  let ansic = "ddd MMM d HH:mm:ss yyyy"
  try:
    discard parse("8:41PM", ansic)
  except ValueError as e:
    p(e.msg)

main()

Nim supports time formatting and parsing via format strings. Here’s how you can work with time in Nim:

  1. We import the necessary modules: times for time-related functions and strformat for string formatting.

  2. The now() function is used to get the current time.

  3. To format a time, we use the format method. Nim uses format strings that are different from Go’s layout constants. For example, “yyyy-MM-dd’T’HH:mm:sszzz” is equivalent to Go’s RFC3339 format.

  4. Parsing a time string is done with the parse function, which takes the time string and the format string as arguments.

  5. Nim allows for custom format strings. You can use various components like “yyyy” for year, “MM” for month, “dd” for day, “HH” for hour, etc.

  6. For numeric representations, you can use Nim’s string formatting capabilities with fmt.

  7. If parsing fails, Nim will raise a ValueError. We can catch this exception to handle parsing errors.

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

2023-06-13T10:30:45+01:00
2012-11-01T22:08:41+00:00 UTC
10:30AM
Tue Jun 13 10:30:45 2023
2023-06-13T10:30:45.123456-07:00
0001-01-01T20:41:00+00:00
2023-06-13T10:30:45-00:00
Invalid format string

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