Source Edit

The times module contains routines and types for dealing with time using the proleptic Gregorian calendar. It’s also available for the JavaScript target.

Although the times module supports nanosecond time resolution, the resolution used by getTime() depends on the platform and backend (JS is limited to millisecond precision).

Examples

  1. import std/[times, os]
  2. # Simple benchmarking
  3. let time = cpuTime()
  4. sleep(100) # Replace this with something to be timed
  5. echo "Time taken: ", cpuTime() - time
  6. # Current date & time
  7. let now1 = now() # Current timestamp as a DateTime in local time
  8. let now2 = now().utc # Current timestamp as a DateTime in UTC
  9. let now3 = getTime() # Current timestamp as a Time
  10. # Arithmetic using Duration
  11. echo "One hour from now : ", now() + initDuration(hours = 1)
  12. # Arithmetic using TimeInterval
  13. echo "One year from now : ", now() + 1.years
  14. echo "One month from now : ", now() + 1.months

Parsing and Formatting Dates

The DateTime type can be parsed and formatted using the different parse and format procedures.

  1. let dt = parse("2000-01-01", "yyyy-MM-dd")
  2. echo dt.format("yyyy-MM-dd")

The different format patterns that are supported are documented below.

PatternDescriptionExample
dNumeric value representing the day of the month, it will be either one or two digits long.

1/04/2012 -> 1
21/04/2012 -> 21

ddSame as above, but is always two digits.

1/04/2012 -> 01
21/04/2012 -> 21

dddThree letter string which indicates the day of the week.

Saturday -> Sat
Monday -> Mon

ddddFull string for the day of the week.

Saturday -> Saturday
Monday -> Monday

GGThe last two digits of the Iso Week-Year

30/12/2012 -> 13

GGGGThe Iso week-calendar year padded to four digits

30/12/2012 -> 2013

hThe hours in one digit if possible. Ranging from 1-12.

5pm -> 5
2am -> 2

hhThe hours in two digits always. If the hour is one digit, 0 is prepended.

5pm -> 05
11am -> 11

HThe hours in one digit if possible, ranging from 0-23.

5pm -> 17
2am -> 2

HHThe hours in two digits always. 0 is prepended if the hour is one digit.

5pm -> 17
2am -> 02

mThe minutes in one digit if possible.

5:30 -> 30
2:01 -> 1

mmSame as above but always two digits, 0 is prepended if the minute is one digit.

5:30 -> 30
2:01 -> 01

MThe month in one digit if possible.

September -> 9
December -> 12

MMThe month in two digits always. 0 is prepended if the month value is one digit.

September -> 09
December -> 12

MMMAbbreviated three-letter form of the month.

September -> Sep
December -> Dec

MMMMFull month string, properly capitalized.

September -> September

sSeconds as one digit if possible.

00:00:06 -> 6

ssSame as above but always two digits. 0 is prepended if the second is one digit.

00:00:06 -> 06

tA when time is in the AM. P when time is in the PM.

5pm -> P
2am -> A

ttSame as above, but AM and PM instead of A and P respectively.

5pm -> PM
2am -> AM

yyThe last two digits of the year. When parsing, the current century is assumed.

2012 AD -> 12

yyyyThe year, padded to at least four digits. Is always positive, even when the year is BC. When the year is more than four digits, ‘+’ is prepended.

2012 AD -> 2012
24 AD -> 0024
24 BC -> 00024
12345 AD -> +12345

YYYYThe year without any padding. Is always positive, even when the year is BC.

2012 AD -> 2012
24 AD -> 24
24 BC -> 24
12345 AD -> 12345

uuuuThe year, padded to at least four digits. Will be negative when the year is BC. When the year is more than four digits, ‘+’ is prepended unless the year is BC.

2012 AD -> 2012
24 AD -> 0024
24 BC -> -0023
12345 AD -> +12345

UUUUThe year without any padding. Will be negative when the year is BC.

2012 AD -> 2012
24 AD -> 24
24 BC -> -23
12345 AD -> 12345

VThe Iso Week-Number as one or two digits

3/2/2012 -> 5
1/4/2012 -> 13

VVThe Iso Week-Number as two digits always. 0 is prepended if one digit.

3/2/2012 -> 05
1/4/2012 -> 13

zDisplays the timezone offset from UTC.

UTC+7 -> +7
UTC-5 -> -5

zzSame as above but with leading 0.

UTC+7 -> +07
UTC-5 -> -05

zzzSame as above but with :mm where mm represents minutes.

UTC+7 -> +07:00
UTC-5 -> -05:00

ZZZSame as above but with mm where mm represents minutes.

UTC+7 -> +0700
UTC-5 -> -0500

zzzzSame as above but with :ss where ss represents seconds.

UTC+7 -> +07:00:00
UTC-5 -> -05:00:00

ZZZZSame as above but with ss where ss represents seconds.

UTC+7 -> +070000
UTC-5 -> -050000

gEra: AD or BC

300 AD -> AD
300 BC -> BC

fffMilliseconds display

1000000 nanoseconds -> 1

ffffffMicroseconds display

1000000 nanoseconds -> 1000

fffffffffNanoseconds display

1000000 nanoseconds -> 1000000

Other strings can be inserted by putting them in ‘’. For example hh’->’mm will give 01->56. The following characters can be inserted without quoting them: : - ( ) / [ ] ,. A literal ‘ can be specified with ‘’.

However you don’t need to necessarily separate format patterns, as an unambiguous format string like yyyyMMddhhmmss is also valid (although only for years in the range 1..9999).

Duration vs TimeInterval

The times module exports two similar types that are both used to represent some amount of time: Duration and TimeInterval. This section explains how they differ and when one should be preferred over the other (short answer: use Duration unless support for months and years is needed).

Duration

A Duration represents a duration of time stored as seconds and nanoseconds. A Duration is always fully normalized, so initDuration(hours = 1) and initDuration(minutes = 60) are equivalent.

Arithmetic with a Duration is very fast, especially when used with the Time type, since it only involves basic arithmetic. Because Duration is more performant and easier to understand it should generally preferred.

TimeInterval

A TimeInterval represents an amount of time expressed in calendar units, for example “1 year and 2 days”. Since some units cannot be normalized (the length of a year is different for leap years for example), the TimeInterval type uses separate fields for every unit. The TimeInterval’s returned from this module generally don’t normalize anything, so even units that could be normalized (like seconds, milliseconds and so on) are left untouched.

Arithmetic with a TimeInterval can be very slow, because it requires timezone information.

Since it’s slower and more complex, the TimeInterval type should be avoided unless the program explicitly needs the features it offers that Duration doesn’t have.

How long is a day?

It should be especially noted that the handling of days differs between TimeInterval and Duration. The Duration type always treats a day as exactly 86400 seconds. For TimeInterval, it’s more complex.

As an example, consider the amount of time between these two timestamps, both in the same timezone:

  • 2018-03-25T12:00+02:00
  • 2018-03-26T12:00+01:00

If only the date & time is considered, it appears that exactly one day has passed. However, the UTC offsets are different, which means that the UTC offset was changed somewhere in between. This happens twice each year for timezones that use daylight savings time. Because of this change, the amount of time that has passed is actually 25 hours.

The TimeInterval type uses calendar units, and will say that exactly one day has passed. The Duration type on the other hand normalizes everything to seconds, and will therefore say that 90000 seconds has passed, which is the same as 25 hours.

See also

Imports

strutils, math, options, since, winlean, time_t

Types

  1. DateTime = object of RootObj

Represents a time in different parts. Although this type can represent leap seconds, they are generally not supported in this module. They are not ignored, but the DateTime’s returned by procedures in this module will never have a leap second. Source Edit

  1. DateTimeLocale = object
  2. MMM*: array[mJan .. mDec, string]
  3. MMMM*: array[mJan .. mDec, string]
  4. ddd*: array[dMon .. dSun, string]
  5. dddd*: array[dMon .. dSun, string]

Source Edit

  1. Duration = object

Represents a fixed duration of time, meaning a duration that has constant length independent of the context.

To create a new Duration, use initDuration. Instead of trying to access the private attributes, use inSeconds for converting to seconds and inNanoseconds for converting to nanoseconds.

Source Edit

  1. DurationParts = array[FixedTimeUnit, int64]

Source Edit

  1. FixedTimeUnit = range[Nanoseconds .. Weeks]

Subrange of TimeUnit that only includes units of fixed duration. These are the units that can be represented by a Duration. Source Edit

  1. HourRange = range[0 .. 23]

Source Edit

  1. IsoWeekRange = range[1 .. 53]

An ISO 8601 calendar week number. Source Edit

  1. IsoYear = distinct int

An ISO 8601 calendar year number.

Warning: The ISO week-based year can correspond to the following or previous year from 29 December to January 3.

Source Edit

  1. MinuteRange = range[0 .. 59]

Source Edit

  1. Month = enum
  2. mJan = (1, "January"), mFeb = "February", mMar = "March", mApr = "April",
  3. mMay = "May", mJun = "June", mJul = "July", mAug = "August",
  4. mSep = "September", mOct = "October", mNov = "November", mDec = "December"

Represents a month. Note that the enum starts at 1, so ord(month) will give the month number in the range 1..12. Source Edit

  1. MonthdayRange = range[1 .. 31]

Source Edit

  1. NanosecondRange = range[0 .. 999999999]

Source Edit

  1. SecondRange = range[0 .. 60]

Includes the value 60 to allow for a leap second. Note however that the second of a DateTime will never be a leap second. Source Edit

  1. Time = object

Represents a point in time. Source Edit

  1. TimeFormat = object
  2. ## \
  3. ## Contains the patterns encoded as bytes.
  4. ## Literal values are encoded in a special way.
  5. ## They start with `Lit.byte`, then the length of the literal, then the
  6. ## raw char values of the literal. For example, the literal `foo` would
  7. ## be encoded as `@[Lit.byte, 3.byte, 'f'.byte, 'o'.byte, 'o'.byte]`.

Represents a format for parsing and printing time types.

To create a new TimeFormat use initTimeFormat proc.

Source Edit

  1. TimeFormatParseError = object of ValueError

Raised when parsing a TimeFormat string fails. Source Edit

  1. TimeInterval = object
  2. nanoseconds*: int ## The number of nanoseconds
  3. microseconds*: int ## The number of microseconds
  4. milliseconds*: int ## The number of milliseconds
  5. seconds*: int ## The number of seconds
  6. minutes*: int ## The number of minutes
  7. hours*: int ## The number of hours
  8. days*: int ## The number of days
  9. weeks*: int ## The number of weeks
  10. months*: int ## The number of months
  11. years*: int ## The number of years

Represents a non-fixed duration of time. Can be used to add and subtract non-fixed time units from a DateTime or Time.

Create a new TimeInterval with initTimeInterval proc.

Note that TimeInterval doesn’t represent a fixed duration of time, since the duration of some units depend on the context (e.g a year can be either 365 or 366 days long). The non-fixed time units are years, months, days and week.

Note that TimeInterval’s returned from the times module are never normalized. If you want to normalize a time unit, Duration should be used instead.

Source Edit

  1. TimeIntervalParts = array[TimeUnit, int]

Source Edit

  1. TimeParseError = object of ValueError

Raised when parsing input using a TimeFormat fails. Source Edit

  1. TimeUnit = enum
  2. Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days, Weeks,
  3. Months, Years

Different units of time. Source Edit

  1. Timezone = ref object

Timezone interface for supporting DateTimes of arbitrary timezones. The times module only supplies implementations for the system’s local time and UTC. Source Edit

  1. WeekDay = enum
  2. dMon = "Monday", dTue = "Tuesday", dWed = "Wednesday", dThu = "Thursday",
  3. dFri = "Friday", dSat = "Saturday", dSun = "Sunday"

Represents a weekday. Source Edit

  1. YeardayRange = range[0 .. 365]

Source Edit

  1. ZonedTime = object
  2. time*: Time ## The point in time being represented.
  3. utcOffset*: int ## The offset in seconds west of UTC,
  4. ## including any offset due to DST.
  5. isDst*: bool ## Determines whether DST is in effect.

Represents a point in time with an associated UTC offset and DST flag. This type is only used for implementing timezones. Source Edit

Consts

  1. DefaultLocale = (MMM: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
  2. "Sep", "Oct", "Nov", "Dec"], MMMM: ["January",
  3. "February", "March", "April", "May", "June", "July", "August", "September",
  4. "October", "November", "December"],
  5. ddd: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], dddd: [
  6. "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])

Source Edit

  1. DurationZero = (seconds: 0, nanosecond: 0)

Zero value for durations. Useful for comparisons.

  1. doAssert initDuration(seconds = 1) > DurationZero
  2. doAssert initDuration(seconds = 0) == DurationZero

Source Edit

Procs

  1. proc `$`(dt: DateTime): string {....tags: [], raises: [], gcsafe, forbids: [].}

Converts a DateTime object to a string representation. It uses the format yyyy-MM-dd’T’HH:mm:sszzz.

Example:

  1. let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc())
  2. doAssert $dt == "2000-01-01T12:00:00Z"
  3. doAssert $default(DateTime) == "Uninitialized DateTime"

Source Edit

  1. proc `$`(dur: Duration): string {....raises: [], tags: [], forbids: [].}

Human friendly string representation of a Duration.

Example:

  1. doAssert $initDuration(seconds = 2) == "2 seconds"
  2. doAssert $initDuration(weeks = 1, days = 2) == "1 week and 2 days"
  3. doAssert $initDuration(hours = 1, minutes = 2, seconds = 3) ==
  4. "1 hour, 2 minutes, and 3 seconds"
  5. doAssert $initDuration(milliseconds = -1500) ==
  6. "-1 second and -500 milliseconds"

Source Edit

  1. proc `$`(f: TimeFormat): string {....raises: [], tags: [], forbids: [].}

Returns the format string that was used to construct f.

Example:

  1. let f = initTimeFormat("yyyy-MM-dd")
  2. doAssert $f == "yyyy-MM-dd"

Source Edit

  1. proc `$`(p: IsoYear): string {.borrow, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `$`(ti: TimeInterval): string {....raises: [], tags: [], forbids: [].}

Get string representation of TimeInterval.

Example:

  1. doAssert $initTimeInterval(years = 1, nanoseconds = 123) ==
  2. "1 year and 123 nanoseconds"
  3. doAssert $initTimeInterval() == "0 nanoseconds"

Source Edit

  1. proc `$`(time: Time): string {....tags: [], raises: [], gcsafe, forbids: [].}

Converts a Time value to a string representation. It will use the local time zone and use the format yyyy-MM-dd’T’HH:mm:sszzz.

Example:

  1. let dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, local())
  2. let tm = dt.toTime()
  3. doAssert $tm == "1970-01-01T00:00:00" & format(dt, "zzz")

Source Edit

  1. proc `$`(zone: Timezone): string {....raises: [], tags: [], forbids: [].}

Returns the name of the timezone. Source Edit

  1. proc `*`(a: Duration; b: int64): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntMulDuration", raises: [], tags: [], forbids: [].}

Multiply a duration by some scalar.

Example:

  1. doAssert initDuration(seconds = 1) * 5 == initDuration(seconds = 5)
  2. doAssert initDuration(minutes = 45) * 3 == initDuration(hours = 2, minutes = 15)

Source Edit

  1. proc `*`(a: int64; b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntMulInt64Duration", raises: [], tags: [], forbids: [].}

Multiply a duration by some scalar.

Example:

  1. doAssert 5 * initDuration(seconds = 1) == initDuration(seconds = 5)
  2. doAssert 3 * initDuration(minutes = 45) == initDuration(hours = 2, minutes = 15)

Source Edit

  1. proc `*=`(a: var Duration; b: int) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+`(a, b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntAddDuration", raises: [],
  3. tags: [], forbids: [].}

Add two durations together.

Example:

  1. doAssert initDuration(seconds = 1) + initDuration(days = 1) ==
  2. initDuration(seconds = 1, days = 1)

Source Edit

  1. proc `+`(a: Time; b: Duration): Time {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntAddTime", raises: [],
  3. tags: [], forbids: [].}

Add a duration of time to a Time.

Example:

  1. doAssert (fromUnix(0) + initDuration(seconds = 1)) == fromUnix(1)

Source Edit

  1. proc `+`(dt: DateTime; dur: Duration): DateTime {....raises: [], tags: [],
  2. forbids: [].}

Example:

  1. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2. let dur = initDuration(hours = 5)
  3. doAssert $(dt + dur) == "2017-03-30T05:00:00Z"

Source Edit

  1. proc `+`(dt: DateTime; interval: TimeInterval): DateTime {....raises: [], tags: [],
  2. forbids: [].}

Adds interval to dt. Components from interval are added in the order of their size, i.e. first the years component, then the months component and so on. The returned DateTime will have the same timezone as the input.

Note that when adding months, monthday overflow is allowed. This means that if the resulting month doesn’t have enough days it, the month will be incremented and the monthday will be set to the number of days overflowed. So adding one month to 31 October will result in 31 November, which will overflow and result in 1 December.

Example:

  1. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2. doAssert $(dt + 1.months) == "2017-04-30T00:00:00Z"
  3. # This is correct and happens due to monthday overflow.
  4. doAssert $(dt - 1.months) == "2017-03-02T00:00:00Z"

Source Edit

  1. proc `+`(ti1, ti2: TimeInterval): TimeInterval {....raises: [], tags: [],
  2. forbids: [].}

Adds two TimeInterval objects together. Source Edit

  1. proc `+`(time: Time; interval: TimeInterval): Time {....raises: [], tags: [],
  2. forbids: [].}

Adds interval to time. If interval contains any years, months, weeks or days the operation is performed in the local timezone.

Example:

  1. let tm = fromUnix(0)
  2. doAssert tm + 5.seconds == fromUnix(5)

Source Edit

  1. proc `+=`(a: var DateTime; b: Duration) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+=`(a: var DateTime; b: TimeInterval) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+=`(a: var TimeInterval; b: TimeInterval) {....raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `+=`(d1: var Duration; d2: Duration) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+=`(t: var Time; b: Duration) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+=`(t: var Time; b: TimeInterval) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-`(a, b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntSubDuration", raises: [],
  3. tags: [], forbids: [].}

Subtract a duration from another.

Example:

  1. doAssert initDuration(seconds = 1, days = 1) - initDuration(seconds = 1) ==
  2. initDuration(days = 1)

Source Edit

  1. proc `-`(a, b: Time): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntDiffTime", raises: [], tags: [],
  3. forbids: [].}

Computes the duration between two points in time.

Example:

  1. doAssert initTime(1000, 100) - initTime(500, 20) ==
  2. initDuration(minutes = 8, seconds = 20, nanoseconds = 80)

Source Edit

  1. proc `-`(a: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntReverseDuration", raises: [],
  3. tags: [], forbids: [].}

Reverse a duration.

Example:

  1. doAssert -initDuration(seconds = 1) == initDuration(seconds = -1)

Source Edit

  1. proc `-`(a: Time; b: Duration): Time {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntSubTime", raises: [],
  3. tags: [], forbids: [].}

Subtracts a duration of time from a Time.

Example:

  1. doAssert (fromUnix(0) - initDuration(seconds = 1)) == fromUnix(-1)

Source Edit

  1. proc `-`(dt1, dt2: DateTime): Duration {....raises: [], tags: [], forbids: [].}

Compute the duration between dt1 and dt2.

Example:

  1. let dt1 = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2. let dt2 = dateTime(2017, mMar, 25, 00, 00, 00, 00, utc())
  3. doAssert dt1 - dt2 == initDuration(days = 5)

Source Edit

  1. proc `-`(dt: DateTime; dur: Duration): DateTime {....raises: [], tags: [],
  2. forbids: [].}

Example:

  1. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2. let dur = initDuration(days = 5)
  3. doAssert $(dt - dur) == "2017-03-25T00:00:00Z"

Source Edit

  1. proc `-`(dt: DateTime; interval: TimeInterval): DateTime {....raises: [], tags: [],
  2. forbids: [].}

Subtract interval from dt. Components from interval are subtracted in the order of their size, i.e. first the years component, then the months component and so on. The returned DateTime will have the same timezone as the input.

Example:

  1. let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
  2. doAssert $(dt - 5.days) == "2017-03-25T00:00:00Z"

Source Edit

  1. proc `-`(ti1, ti2: TimeInterval): TimeInterval {....raises: [], tags: [],
  2. forbids: [].}

Subtracts TimeInterval ti1 from ti2.

Time components are subtracted one-by-one, see output:

Example:

  1. let ti1 = initTimeInterval(hours = 24)
  2. let ti2 = initTimeInterval(hours = 4)
  3. doAssert (ti1 - ti2) == initTimeInterval(hours = 20)

Source Edit

  1. proc `-`(ti: TimeInterval): TimeInterval {....raises: [], tags: [], forbids: [].}

Reverses a time interval

Example:

  1. let day = -initTimeInterval(hours = 24)
  2. doAssert day.hours == -24

Source Edit

  1. proc `-`(time: Time; interval: TimeInterval): Time {....raises: [], tags: [],
  2. forbids: [].}

Subtracts interval from Time time. If interval contains any years, months, weeks or days the operation is performed in the local timezone.

Example:

  1. let tm = fromUnix(5)
  2. doAssert tm - 5.seconds == fromUnix(0)

Source Edit

  1. proc `-=`(a: var DateTime; b: Duration) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-=`(a: var DateTime; b: TimeInterval) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-=`(a: var TimeInterval; b: TimeInterval) {....raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `-=`(dt: var Duration; ti: Duration) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-=`(t: var Time; b: Duration) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-=`(t: var Time; b: TimeInterval) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}

Returns true if a happened before b. Source Edit

  1. proc `<`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntLtDuration", raises: [], tags: [],
  3. forbids: [].}

Note that a duration can be negative, so even if a < b is true a might represent a larger absolute duration. Use abs(a) < abs(b) to compare the absolute duration.

Example:

  1. doAssert initDuration(seconds = 1) < initDuration(seconds = 2)
  2. doAssert initDuration(seconds = -2) < initDuration(seconds = 1)
  3. doAssert initDuration(seconds = -2).abs < initDuration(seconds = 1).abs == false

Source Edit

  1. proc `<`(a, b: Time): bool {....gcsafe, noSideEffect, ...gcsafe, extern: "ntLtTime",
  2. raises: [], tags: [], forbids: [].}

Returns true if a < b, that is if a happened before b.

Example:

  1. doAssert initTime(50, 0) < initTime(99, 0)

Source Edit

  1. proc `<=`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}

Returns true if a happened before or at the same time as b. Source Edit

  1. proc `<=`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntLeDuration", raises: [], tags: [],
  3. forbids: [].}

Source Edit

  1. proc `<=`(a, b: Time): bool {....gcsafe, noSideEffect, ...gcsafe, extern: "ntLeTime",
  2. raises: [], tags: [], forbids: [].}

Returns true if a <= b. Source Edit

  1. proc `==`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}

Returns true if a and b represent the same point in time. Source Edit

  1. proc `==`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntEqDuration", raises: [], tags: [],
  3. forbids: [].}

Example:

  1. let
  2. d1 = initDuration(weeks = 1)
  3. d2 = initDuration(days = 7)
  4. doAssert d1 == d2

Source Edit

  1. proc `==`(a, b: IsoYear): bool {.borrow, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `==`(a, b: Time): bool {....gcsafe, noSideEffect, ...gcsafe, extern: "ntEqTime",
  2. raises: [], tags: [], forbids: [].}

Returns true if a == b, that is if both times represent the same point in time. Source Edit

  1. proc `==`(zone1, zone2: Timezone): bool {....raises: [], tags: [], forbids: [].}

Two Timezone’s are considered equal if their name is equal.

Example:

  1. doAssert local() == local()
  2. doAssert local() != utc()

Source Edit

  1. proc abs(a: Duration): Duration {....raises: [], tags: [], forbids: [].}

Example:

  1. doAssert initDuration(milliseconds = -1500).abs ==
  2. initDuration(milliseconds = 1500)

Source Edit

  1. proc between(startDt, endDt: DateTime): TimeInterval {....raises: [], tags: [],
  2. forbids: [].}

Gives the difference between startDt and endDt as a TimeInterval. The following guarantees about the result is given:

  • All fields will have the same sign.
  • If startDt.timezone == endDt.timezone, it is guaranteed that startDt + between(startDt, endDt) == endDt.
  • If startDt.timezone != endDt.timezone, then the result will be equivalent to between(startDt.utc, endDt.utc).

Example:

  1. var a = dateTime(2015, mMar, 25, 12, 0, 0, 00, utc())
  2. var b = dateTime(2017, mApr, 1, 15, 0, 15, 00, utc())
  3. var ti = initTimeInterval(years = 2, weeks = 1, hours = 3, seconds = 15)
  4. doAssert between(a, b) == ti
  5. doAssert between(a, b) == -between(b, a)

Source Edit

  1. proc convert[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit; quantity: T): T {.
  2. inline.}

Convert a quantity of some duration unit to another duration unit. This proc only deals with integers, so the result might be truncated.

Example:

  1. doAssert convert(Days, Hours, 2) == 48
  2. doAssert convert(Days, Weeks, 13) == 1 # Truncated
  3. doAssert convert(Seconds, Milliseconds, -1) == -1000

Source Edit

  1. proc cpuTime(): float {....tags: [TimeEffect], raises: [], forbids: [].}

Gets time spent that the CPU spent to run the current process in seconds. This may be more useful for benchmarking than epochTime. However, it may measure the real time instead (depending on the OS). The value of the result has no meaning. To generate useful timing values, take the difference between the results of two cpuTime calls:

Example:

  1. var t0 = cpuTime()
  2. # some useless work here (calculate fibonacci)
  3. var fib = @[0, 1, 1]
  4. for i in 1..10:
  5. fib.add(fib[^1] + fib[^2])
  6. echo "CPU time [s] ", cpuTime() - t0
  7. echo "Fib is [s] ", fib

When the flag --benchmarkVM is passed to the compiler, this proc is also available at compile time Source Edit

  1. proc dateTime(year: int; month: Month; monthday: MonthdayRange;
  2. hour: HourRange = 0; minute: MinuteRange = 0;
  3. second: SecondRange = 0; nanosecond: NanosecondRange = 0;
  4. zone: Timezone = local()): DateTime {....raises: [], tags: [],
  5. forbids: [].}

Create a new DateTime in the specified timezone.

Example:

  1. assert $dateTime(2017, mMar, 30, zone = utc()) == "2017-03-30T00:00:00Z"

Source Edit

  1. proc days(d: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of d days.

echo getTime() + 2.days

Source Edit

  1. proc `div`(a: Duration; b: int64): Duration {....gcsafe, noSideEffect, ...gcsafe,
  2. extern: "ntDivDuration", raises: [], tags: [], forbids: [].}

Integer division for durations.

Example:

  1. doAssert initDuration(seconds = 3) div 2 ==
  2. initDuration(milliseconds = 1500)
  3. doAssert initDuration(minutes = 45) div 30 ==
  4. initDuration(minutes = 1, seconds = 30)
  5. doAssert initDuration(nanoseconds = 3) div 2 ==
  6. initDuration(nanoseconds = 1)

Source Edit

  1. proc epochTime(): float {....tags: [TimeEffect], raises: [], forbids: [].}

Gets time after the UNIX epoch (1970) in seconds. It is a float because sub-second resolution is likely to be supported (depending on the hardware/OS).

getTime should generally be preferred over this proc.

Warning: Unsuitable for benchmarking (but still better than now), use monotimes.getMonoTime or cpuTime instead, depending on the use case.

Source Edit

  1. proc format(dt: DateTime; f: static[string]): string {....raises: [].}

Overload that validates format at compile time. Source Edit

  1. proc format(dt: DateTime; f: string; loc: DateTimeLocale = DefaultLocale): string {.
  2. ...raises: [TimeFormatParseError], tags: [], forbids: [].}

Shorthand for constructing a TimeFormat and using it to format dt.

See Parsing and formatting dates for documentation of the format argument.

Example:

  1. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  2. doAssert "2000-01-01" == format(dt, "yyyy-MM-dd")

Source Edit

  1. proc format(dt: DateTime; f: TimeFormat; loc: DateTimeLocale = DefaultLocale): string {.
  2. ...raises: [], tags: [], forbids: [].}

Format dt using the format specified by f.

Example:

  1. let f = initTimeFormat("yyyy-MM-dd")
  2. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  3. doAssert "2000-01-01" == dt.format(f)

Source Edit

  1. proc format(time: Time; f: static[string]; zone: Timezone = local()): string {.
  2. ...raises: [].}

Overload that validates f at compile time. Source Edit

  1. proc format(time: Time; f: string; zone: Timezone = local()): string {.
  2. ...raises: [TimeFormatParseError], tags: [], forbids: [].}

Shorthand for constructing a TimeFormat and using it to format time. Will use the timezone specified by zone.

See Parsing and formatting dates for documentation of the f argument.

Example:

  1. var dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, utc())
  2. var tm = dt.toTime()
  3. doAssert format(tm, "yyyy-MM-dd'T'HH:mm:ss", utc()) == "1970-01-01T00:00:00"

Source Edit

  1. proc formatValue(result: var string; value: DateTime | Time; specifier: string)

adapter for strformat. Not intended to be called directly. Source Edit

  1. proc fromUnix(unix: int64): Time {....gcsafe, tags: [], raises: [], noSideEffect,
  2. ...forbids: [].}

Convert a unix timestamp (seconds since 1970-01-01T00:00:00Z) to a Time.

Example:

  1. doAssert $fromUnix(0).utc == "1970-01-01T00:00:00Z"

Source Edit

  1. proc fromUnixFloat(seconds: float): Time {....gcsafe, tags: [], raises: [],
  2. noSideEffect, ...forbids: [].}

Convert a unix timestamp in seconds to a Time; same as fromUnix but with subsecond resolution.

Example:

  1. doAssert fromUnixFloat(123456.0) == fromUnixFloat(123456)
  2. doAssert fromUnixFloat(-123456.0) == fromUnixFloat(-123456)

Source Edit

  1. proc fromWinTime(win: int64): Time {....raises: [], tags: [], forbids: [].}

Convert a Windows file time (100-nanosecond intervals since 1601-01-01T00:00:00Z) to a Time. Source Edit

  1. proc getClockStr(dt = now()): string {....gcsafe, extern: "nt$1",
  2. tags: [TimeEffect], raises: [],
  3. forbids: [].}

Gets the current local clock time as a string of the format HH:mm:ss.

Example:

  1. echo getClockStr(now() - 1.hours)

Source Edit

  1. proc getDateStr(dt = now()): string {....gcsafe, extern: "nt$1",
  2. tags: [TimeEffect], raises: [],
  3. forbids: [].}

Gets the current local date as a string of the format YYYY-MM-DD.

Example:

  1. echo getDateStr(now() - 1.months)

Source Edit

  1. proc getDayOfWeek(monthday: MonthdayRange; month: Month; year: int): WeekDay {.
  2. ...tags: [], raises: [], gcsafe, forbids: [].}

Returns the day of the week enum from day, month and year. Equivalent with dateTime(year, month, monthday, 0, 0, 0, 0).weekday.

Example:

  1. doAssert getDayOfWeek(13, mJun, 1990) == dWed
  2. doAssert $getDayOfWeek(13, mJun, 1990) == "Wednesday"

Source Edit

  1. proc getDayOfYear(monthday: MonthdayRange; month: Month; year: int): YeardayRange {.
  2. ...tags: [], raises: [], gcsafe, forbids: [].}

Returns the day of the year. Equivalent with dateTime(year, month, monthday, 0, 0, 0, 0).yearday.

Example:

  1. doAssert getDayOfYear(1, mJan, 2000) == 0
  2. doAssert getDayOfYear(10, mJan, 2000) == 9
  3. doAssert getDayOfYear(10, mFeb, 2000) == 40

Source Edit

  1. proc getDaysInMonth(month: Month; year: int): int {....raises: [], tags: [],
  2. forbids: [].}

Get the number of days in month of year.

Example:

  1. doAssert getDaysInMonth(mFeb, 2000) == 29
  2. doAssert getDaysInMonth(mFeb, 2001) == 28

Source Edit

  1. proc getDaysInYear(year: int): int {....raises: [], tags: [], forbids: [].}

Get the number of days in a year

Example:

  1. doAssert getDaysInYear(2000) == 366
  2. doAssert getDaysInYear(2001) == 365

Source Edit

  1. proc getIsoWeekAndYear(dt: DateTime): tuple[isoweek: IsoWeekRange,
  2. isoyear: IsoYear] {....raises: [], tags: [], forbids: [].}

Returns the ISO 8601 week and year.

Warning: The ISO week-based year can correspond to the following or previous year from 29 December to January 3.

Example:

  1. assert getIsoWeekAndYear(initDateTime(21, mApr, 2018, 00, 00, 00)) == (isoweek: 16.IsoWeekRange, isoyear: 2018.IsoYear)
  2. block:
  3. let (w, y) = getIsoWeekAndYear(initDateTime(30, mDec, 2019, 00, 00, 00))
  4. assert w == 01.IsoWeekRange
  5. assert y == 2020.IsoYear
  6. assert getIsoWeekAndYear(initDateTime(13, mSep, 2020, 00, 00, 00)) == (isoweek: 37.IsoWeekRange, isoyear: 2020.IsoYear)
  7. block:
  8. let (w, y) = getIsoWeekAndYear(initDateTime(2, mJan, 2021, 00, 00, 00))
  9. assert w.int > 52
  10. assert w.int < 54
  11. assert y.int mod 100 == 20

Source Edit

  1. proc getTime(): Time {....tags: [TimeEffect], gcsafe, raises: [], forbids: [].}

Gets the current time as a Time with up to nanosecond resolution. Source Edit

  1. proc getWeeksInIsoYear(y: IsoYear): IsoWeekRange {....raises: [], tags: [],
  2. forbids: [].}

Returns the number of weeks in the specified ISO 8601 week-based year, which can be either 53 or 52.

Example:

  1. assert getWeeksInIsoYear(IsoYear(2019)) == 52
  2. assert getWeeksInIsoYear(IsoYear(2020)) == 53

Source Edit

  1. proc high(typ: typedesc[Duration]): Duration

Get the longest representable duration. Source Edit

  1. proc high(typ: typedesc[Time]): Time

Source Edit

  1. proc hour(dt: DateTime): HourRange {.inline, ...raises: [], tags: [], forbids: [].}

The number of hours past midnight, in the range 0 to 23. Source Edit

  1. proc hour=(dt: var DateTime; value: HourRange) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc hours(h: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of h hours.

echo getTime() + 2.hours

Source Edit

  1. proc inDays(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole days.

Example:

  1. let dur = initDuration(hours = -50)
  2. doAssert dur.inDays == -2

Source Edit

  1. proc inHours(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole hours.

Example:

  1. let dur = initDuration(minutes = 60, days = 2)
  2. doAssert dur.inHours == 49

Source Edit

  1. proc initDateTime(monthday: MonthdayRange; month: Month; year: int;
  2. hour: HourRange; minute: MinuteRange; second: SecondRange;
  3. nanosecond: NanosecondRange; zone: Timezone = local()): DateTime {.
  4. ...deprecated: "use `dateTime`", raises: [], tags: [], forbids: [].}

Deprecated: use `dateTime`

Create a new DateTime in the specified timezone.

Example: cmd: —warning:deprecated:off

  1. assert $initDateTime(30, mMar, 2017, 00, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"

Source Edit

  1. proc initDateTime(monthday: MonthdayRange; month: Month; year: int;
  2. hour: HourRange; minute: MinuteRange; second: SecondRange;
  3. zone: Timezone = local()): DateTime {.
  4. ...deprecated: "use `dateTime`", raises: [], tags: [], forbids: [].}

Deprecated: use `dateTime`

Create a new DateTime in the specified timezone.

Example: cmd: —warning:deprecated:off

  1. assert $initDateTime(30, mMar, 2017, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"

Source Edit

  1. proc initDateTime(weekday: WeekDay; isoweek: IsoWeekRange; isoyear: IsoYear;
  2. hour: HourRange; minute: MinuteRange; second: SecondRange;
  3. nanosecond: NanosecondRange; zone: Timezone = local()): DateTime {.
  4. ...gcsafe, raises: [], tags: [], forbids: [].}

Source Edit

  1. proc initDateTime(weekday: WeekDay; isoweek: IsoWeekRange; isoyear: IsoYear;
  2. hour: HourRange; minute: MinuteRange; second: SecondRange;
  3. zone: Timezone = local()): DateTime {....gcsafe, raises: [],
  4. tags: [], forbids: [].}

Source Edit

  1. proc initDuration(nanoseconds, microseconds, milliseconds, seconds, minutes,
  2. hours, days, weeks: int64 = 0): Duration {....raises: [],
  3. tags: [], forbids: [].}

Create a new Duration.

Example:

  1. let dur = initDuration(seconds = 1, milliseconds = 1)
  2. doAssert dur.inMilliseconds == 1001
  3. doAssert dur.inSeconds == 1

Source Edit

  1. proc initTime(unix: int64; nanosecond: NanosecondRange): Time {....raises: [],
  2. tags: [], forbids: [].}

Create a Time from a unix timestamp and a nanosecond part. Source Edit

  1. proc initTimeFormat(format: string): TimeFormat {.
  2. ...raises: [TimeFormatParseError], tags: [], forbids: [].}

Construct a new time format for parsing & formatting time types.

See Parsing and formatting dates for documentation of the format argument.

Example:

  1. let f = initTimeFormat("yyyy-MM-dd")
  2. doAssert "2000-01-01" == "2000-01-01".parse(f).format(f)

Source Edit

  1. proc initTimeInterval(nanoseconds, microseconds, milliseconds, seconds, minutes,
  2. hours, days, weeks, months, years: int = 0): TimeInterval {.
  3. ...raises: [], tags: [], forbids: [].}

Creates a new TimeInterval.

This proc doesn’t perform any normalization! For example, initTimeInterval(hours = 24) and initTimeInterval(days = 1) are not equal.

You can also use the convenience procedures called milliseconds, seconds, minutes, hours, days, months, and years.

Example:

  1. let day = initTimeInterval(hours = 24)
  2. let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc())
  3. doAssert $(dt + day) == "2000-01-02T12:00:00Z"
  4. doAssert initTimeInterval(hours = 24) != initTimeInterval(days = 1)

Source Edit

  1. proc inMicroseconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole microseconds.

Example:

  1. let dur = initDuration(seconds = -2)
  2. doAssert dur.inMicroseconds == -2000000

Source Edit

  1. proc inMilliseconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole milliseconds.

Example:

  1. let dur = initDuration(seconds = -2)
  2. doAssert dur.inMilliseconds == -2000

Source Edit

  1. proc inMinutes(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole minutes.

Example:

  1. let dur = initDuration(hours = 2, seconds = 10)
  2. doAssert dur.inMinutes == 120

Source Edit

  1. proc inNanoseconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole nanoseconds.

Example:

  1. let dur = initDuration(seconds = -2)
  2. doAssert dur.inNanoseconds == -2000000000

Source Edit

  1. proc inSeconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole seconds.

Example:

  1. let dur = initDuration(hours = 2, milliseconds = 10)
  2. doAssert dur.inSeconds == 2 * 60 * 60

Source Edit

  1. proc inWeeks(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}

Converts the duration to the number of whole weeks.

Example:

  1. let dur = initDuration(days = 8)
  2. doAssert dur.inWeeks == 1

Source Edit

  1. proc inZone(dt: DateTime; zone: Timezone): DateTime {....tags: [], raises: [],
  2. gcsafe, forbids: [].}

Returns a DateTime representing the same point in time as dt but using zone as the timezone. Source Edit

  1. proc inZone(time: Time; zone: Timezone): DateTime {....tags: [], raises: [],
  2. gcsafe, forbids: [].}

Convert time into a DateTime using zone as the timezone. Source Edit

  1. proc isDst(dt: DateTime): bool {.inline, ...raises: [], tags: [], forbids: [].}

Determines whether DST is in effect. Always false for the JavaScript backend. Source Edit

  1. proc isDst=(dt: var DateTime; value: bool) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc isInitialized(dt: DateTime): bool {....raises: [], tags: [], forbids: [].}

Example:

  1. doAssert now().isInitialized
  2. doAssert not default(DateTime).isInitialized

Source Edit

  1. proc isLeapDay(dt: DateTime): bool {....raises: [], tags: [], forbids: [].}

Returns whether t is a leap day, i.e. Feb 29 in a leap year. This matters as it affects time offset calculations.

Example:

  1. let dt = dateTime(2020, mFeb, 29, 00, 00, 00, 00, utc())
  2. doAssert dt.isLeapDay
  3. doAssert dt+1.years-1.years != dt
  4. let dt2 = dateTime(2020, mFeb, 28, 00, 00, 00, 00, utc())
  5. doAssert not dt2.isLeapDay
  6. doAssert dt2+1.years-1.years == dt2
  7. doAssertRaises(Exception): discard dateTime(2021, mFeb, 29, 00, 00, 00, 00, utc())

Source Edit

  1. proc isLeapYear(year: int): bool {....raises: [], tags: [], forbids: [].}

Returns true if year is a leap year.

Example:

  1. doAssert isLeapYear(2000)
  2. doAssert not isLeapYear(1900)

Source Edit

  1. proc local(): Timezone {....raises: [], tags: [], forbids: [].}

Get the Timezone implementation for the local timezone.

Example:

  1. doAssert now().timezone == local()
  2. doAssert local().name == "LOCAL"

Source Edit

  1. proc local(dt: DateTime): DateTime {....raises: [], tags: [], forbids: [].}

Shorthand for dt.inZone(local()). Source Edit

  1. proc local(t: Time): DateTime {....raises: [], tags: [], forbids: [].}

Shorthand for t.inZone(local()). Source Edit

  1. proc low(typ: typedesc[Duration]): Duration

Get the longest representable duration of negative direction. Source Edit

  1. proc low(typ: typedesc[Time]): Time

Source Edit

  1. proc microseconds(micros: int): TimeInterval {.inline, ...raises: [], tags: [],
  2. forbids: [].}

TimeInterval of micros microseconds. Source Edit

  1. proc milliseconds(ms: int): TimeInterval {.inline, ...raises: [], tags: [],
  2. forbids: [].}

TimeInterval of ms milliseconds. Source Edit

  1. proc minute(dt: DateTime): MinuteRange {.inline, ...raises: [], tags: [],
  2. forbids: [].}

The number of minutes after the hour, in the range 0 to 59. Source Edit

  1. proc minute=(dt: var DateTime; value: MinuteRange) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc minutes(m: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of m minutes.

echo getTime() + 5.minutes

Source Edit

  1. proc month(dt: DateTime): Month {....raises: [], tags: [], forbids: [].}

The month as an enum, the ordinal value is in the range 1 to 12. Source Edit

  1. proc monthday(dt: DateTime): MonthdayRange {.inline, ...raises: [], tags: [],
  2. forbids: [].}

The day of the month, in the range 1 to 31. Source Edit

  1. proc monthdayZero=(dt: var DateTime; value: int) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc months(m: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of m months.

echo getTime() + 2.months

Source Edit

  1. proc monthZero=(dt: var DateTime; value: int) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc name(zone: Timezone): string {....raises: [], tags: [], forbids: [].}

The name of the timezone.

If possible, the name will be the name used in the tz database. If the timezone doesn’t exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously might be used. For example, the string “LOCAL” is used for the system’s local timezone.

See also: https://en.wikipedia.org/wiki/Tz_database

Source Edit

  1. proc nanosecond(dt: DateTime): NanosecondRange {.inline, ...raises: [], tags: [],
  2. forbids: [].}

The number of nanoseconds after the second, in the range 0 to 999_999_999. Source Edit

  1. proc nanosecond(time: Time): NanosecondRange {....raises: [], tags: [], forbids: [].}

Get the fractional part of a Time as the number of nanoseconds of the second. Source Edit

  1. proc nanosecond=(dt: var DateTime; value: NanosecondRange) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc nanoseconds(nanos: int): TimeInterval {.inline, ...raises: [], tags: [],
  2. forbids: [].}

TimeInterval of nanos nanoseconds. Source Edit

  1. proc newTimezone(name: string; zonedTimeFromTimeImpl: proc (time: Time): ZonedTime {.
  2. ...tags: [], raises: [], gcsafe.}; zonedTimeFromAdjTimeImpl: proc (
  3. adjTime: Time): ZonedTime {....tags: [], raises: [], gcsafe.}): owned Timezone {.
  4. ...raises: [], tags: [], forbids: [].}

Create a new Timezone.

zonedTimeFromTimeImpl and zonedTimeFromAdjTimeImpl is used as the underlying implementations for zonedTimeFromTime and zonedTimeFromAdjTime.

If possible, the name parameter should match the name used in the tz database. If the timezone doesn’t exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously can be used. Note that the timezones name is used for checking equality!

Example:

  1. proc utcTzInfo(time: Time): ZonedTime =
  2. ZonedTime(utcOffset: 0, isDst: false, time: time)
  3. let utc = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)

Source Edit

  1. proc now(): DateTime {....tags: [TimeEffect], gcsafe, raises: [], forbids: [].}

Get the current time as a DateTime in the local timezone. Shorthand for getTime().local.

Warning: Unsuitable for benchmarking, use monotimes.getMonoTime or cpuTime instead, depending on the use case.

Source Edit

  1. proc parse(input, f: string; tz: Timezone = local();
  2. loc: DateTimeLocale = DefaultLocale): DateTime {.
  3. ...raises: [TimeParseError, TimeFormatParseError], tags: [TimeEffect],
  4. forbids: [].}

Shorthand for constructing a TimeFormat and using it to parse input as a DateTime.

See Parsing and formatting dates for documentation of the f argument.

Example:

  1. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  2. doAssert dt == parse("2000-01-01", "yyyy-MM-dd", utc())

Source Edit

  1. proc parse(input: string; f: static[string]; zone: Timezone = local();
  2. loc: DateTimeLocale = DefaultLocale): DateTime {.
  3. ...raises: [TimeParseError].}

Overload that validates f at compile time. Source Edit

  1. proc parse(input: string; f: TimeFormat; zone: Timezone = local();
  2. loc: DateTimeLocale = DefaultLocale): DateTime {.
  3. ...raises: [TimeParseError], tags: [TimeEffect], forbids: [].}

Parses input as a DateTime using the format specified by f. If no UTC offset was parsed, then input is assumed to be specified in the zone timezone. If a UTC offset was parsed, the result will be converted to the zone timezone.

Month and day names from the passed in loc are used.

Example:

  1. let f = initTimeFormat("yyyy-MM-dd")
  2. let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
  3. doAssert dt == "2000-01-01".parse(f, utc())

Source Edit

  1. proc parseTime(input, f: string; zone: Timezone): Time {.
  2. ...raises: [TimeParseError, TimeFormatParseError], tags: [TimeEffect],
  3. forbids: [].}

Shorthand for constructing a TimeFormat and using it to parse input as a DateTime, then converting it a Time.

See Parsing and formatting dates for documentation of the format argument.

Example:

  1. let tStr = "1970-01-01T00:00:00+00:00"
  2. doAssert parseTime(tStr, "yyyy-MM-dd'T'HH:mm:sszzz", utc()) == fromUnix(0)

Source Edit

  1. proc parseTime(input: string; f: static[string]; zone: Timezone): Time {.
  2. ...raises: [TimeParseError].}

Overload that validates format at compile time. Source Edit

  1. proc second(dt: DateTime): SecondRange {.inline, ...raises: [], tags: [],
  2. forbids: [].}

The number of seconds after the minute, in the range 0 to 59. Source Edit

  1. proc second=(dt: var DateTime; value: SecondRange) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc seconds(s: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of s seconds.

echo getTime() + 5.seconds

Source Edit

  1. proc timezone(dt: DateTime): Timezone {.inline, ...raises: [], tags: [],
  2. forbids: [].}

The timezone represented as an implementation of Timezone. Source Edit

  1. proc timezone=(dt: var DateTime; value: Timezone) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc toParts(dur: Duration): DurationParts {....raises: [], tags: [], forbids: [].}

Converts a duration into an array consisting of fixed time units.

Each value in the array gives information about a specific unit of time, for example result[Days] gives a count of days.

This procedure is useful for converting Duration values to strings.

Example:

  1. var dp = toParts(initDuration(weeks = 2, days = 1))
  2. doAssert dp[Days] == 1
  3. doAssert dp[Weeks] == 2
  4. doAssert dp[Minutes] == 0
  5. dp = toParts(initDuration(days = -1))
  6. doAssert dp[Days] == -1

Source Edit

  1. proc toParts(ti: TimeInterval): TimeIntervalParts {....raises: [], tags: [],
  2. forbids: [].}

Converts a TimeInterval into an array consisting of its time units, starting with nanoseconds and ending with years.

This procedure is useful for converting TimeInterval values to strings. E.g. then you need to implement custom interval printing

Example:

  1. var tp = toParts(initTimeInterval(years = 1, nanoseconds = 123))
  2. doAssert tp[Years] == 1
  3. doAssert tp[Nanoseconds] == 123

Source Edit

  1. proc toTime(dt: DateTime): Time {....tags: [], raises: [], gcsafe, forbids: [].}

Converts a DateTime to a Time representing the same point in time. Source Edit

  1. proc toUnix(t: Time): int64 {....gcsafe, tags: [], raises: [], noSideEffect,
  2. ...forbids: [].}

Convert t to a unix timestamp (seconds since 1970-01-01T00:00:00Z). See also toUnixFloat for subsecond resolution.

Example:

  1. doAssert fromUnix(0).toUnix() == 0

Source Edit

  1. proc toUnixFloat(t: Time): float {....gcsafe, tags: [], raises: [], forbids: [].}

Same as toUnix but using subsecond resolution.

Example:

  1. let t = getTime()
  2. # `<` because of rounding errors
  3. doAssert abs(t.toUnixFloat().fromUnixFloat - t) < initDuration(nanoseconds = 1000)

Source Edit

  1. proc toWinTime(t: Time): int64 {....raises: [], tags: [], forbids: [].}

Convert t to a Windows file time (100-nanosecond intervals since 1601-01-01T00:00:00Z). Source Edit

  1. proc utc(): Timezone {....raises: [], tags: [], forbids: [].}

Get the Timezone implementation for the UTC timezone.

Example:

  1. doAssert now().utc.timezone == utc()
  2. doAssert utc().name == "Etc/UTC"

Source Edit

  1. proc utc(dt: DateTime): DateTime {....raises: [], tags: [], forbids: [].}

Shorthand for dt.inZone(utc()). Source Edit

  1. proc utc(t: Time): DateTime {....raises: [], tags: [], forbids: [].}

Shorthand for t.inZone(utc()). Source Edit

  1. proc utcOffset(dt: DateTime): int {.inline, ...raises: [], tags: [], forbids: [].}

The offset in seconds west of UTC, including any offset due to DST. Note that the sign of this number is the opposite of the one in a formatted offset string like +01:00 (which would be equivalent to the UTC offset -3600). Source Edit

  1. proc utcOffset=(dt: var DateTime; value: int) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc weekday(dt: DateTime): WeekDay {.inline, ...raises: [], tags: [], forbids: [].}

The day of the week as an enum, the ordinal value is in the range 0 (monday) to 6 (sunday). Source Edit

  1. proc weekday=(dt: var DateTime; value: WeekDay) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc weeks(w: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of w weeks.

echo getTime() + 2.weeks

Source Edit

  1. proc year(dt: DateTime): int {.inline, ...raises: [], tags: [], forbids: [].}

The year, using astronomical year numbering (meaning that before year 1 is year 0, then year -1 and so on). Source Edit

  1. proc year=(dt: var DateTime; value: int) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc yearday(dt: DateTime): YeardayRange {.inline, ...raises: [], tags: [],
  2. forbids: [].}

The number of days since January 1, in the range 0 to 365. Source Edit

  1. proc yearday=(dt: var DateTime; value: YeardayRange) {.
  2. ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}

Deprecated: Deprecated since v1.3.1

Source Edit

  1. proc years(y: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}

TimeInterval of y years.

echo getTime() + 2.years

Source Edit

  1. proc zonedTimeFromAdjTime(zone: Timezone; adjTime: Time): ZonedTime {.
  2. ...raises: [], tags: [], forbids: [].}

Returns the ZonedTime for some local time.

Note that the Time argument does not represent a point in time, it represent a local time! E.g if adjTime is fromUnix(0), it should be interpreted as 1970-01-01T00:00:00 in the zone timezone, not in UTC.

Source Edit

  1. proc zonedTimeFromTime(zone: Timezone; time: Time): ZonedTime {....raises: [],
  2. tags: [], forbids: [].}

Returns the ZonedTime for some point in time. Source Edit