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:
We use the
times
module for time-related operations.The
now()
function gets the current time.We create a specific time using
initDateTime()
, which is similar to thetime.Date()
function in the original example.We can extract various components of a time value (year, month, day, etc.) using properties of the
DateTime
object.Comparison between times is done using the standard comparison operators (
<
,>
,==
).The difference between two times is calculated using the
-
operator, which returns aDuration
object.We can get the duration in various units (hours, minutes, seconds, nanoseconds) using methods of the
Duration
object.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.