Time in Nim

import std/times
import std/strformat

proc main() =
  let p = proc(x: auto) = echo x

  # We'll start by getting the current time.
  let now = now()
  p(now)

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

  # You can extract the various components of the time
  # value as expected.
  p(then.year)
  p(then.month)
  p(then.monthday)
  p(then.hour)
  p(then.minute)
  p(then.second)
  p(then.nanosecond)
  p(then.timezone)

  # The Monday-Sunday weekday is also available.
  p(then.weekday)

  # 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 Duration representing
  # the interval between two times.
  let diff = now - then
  p(diff)

  # We can compute the length of the duration in
  # various units.
  p(diff.inHours)
  p(diff.inMinutes)
  p(diff.inSeconds)
  p(diff.inNanoseconds)

  # 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)

main()

This Nim code demonstrates working with times and durations. Here’s a breakdown of the main concepts:

  1. We use the times module for time-related operations.

  2. The now() function gets the current time.

  3. We create a specific time using initDateTime(), which is similar to the time.Date() function in the original example.

  4. We can extract various components of a time value (year, month, day, etc.) using properties of the DateTime object.

  5. Comparison between times is done using the standard comparison operators (<, >, ==).

  6. The difference between two times is calculated using the - operator, which returns a Duration object.

  7. We can get the duration in various units (hours, minutes, seconds, nanoseconds) using methods of the Duration object.

  8. We can add or subtract durations from times using the + and - operators.

To run this program, save it as time_example.nim and use the Nim compiler:

$ nim c -r time_example.nim

This will compile and run the program, showing output similar to the original example but with current dates and times.

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