Skip to content

DateTime

A UTC instant, held as Unix nanoseconds.

There is no constructor; use now, from_unix or parse_rfc.

Class Methods

from_unix … -> DateTime

Builds an instant from a Unix timestamp.

At least one of seconds and nanos must be given. When both are, nanos is added to seconds, which is how a whole-seconds timestamp and a sub-second remainder are combined without going through a float.

Parameters

NameTypeDescription
seconds? (Int | Float) Seconds since the Unix epoch.
:nanos? Int Nanoseconds since the Unix epoch, or, when seconds is also given, nanoseconds to add to it.

Errors

Exception Condition
TypeError Neither argument was given
OverflowError The combined timestamp does not fit

Example

echo $ DateTime.from_unix 1700000000
echo $ DateTime.from_unix 1.25
echo $ DateTime.from_unix nanos: 1700000000123000000
echo $ DateTime.from_unix 1700000000 nanos: 123000000

now() -> DateTime

Returns the current UTC instant.

Example

echo $DateTime.now()

parse_rfc text -> DateTime

Parses an RFC 3339 date-time.

An offset is required, and is applied to give the UTC instant; the offset itself is not retained.

Parameters

NameTypeDescription
text Str Date-time text.

Errors

DataError if the input is not a valid RFC 3339 string.

Example

let dt = DateTime.parse_rfc("2024-01-02T03:04:05Z")
assert_eq $dt.rfc() "2024-01-02T03:04:05Z"
Open in playground

Fields

unix_nanos @ Int [get]

Unix nanoseconds. Exact.

unix_secs @ Float [get]

Unix seconds. Approximate: far-from-epoch instants lose sub-second precision.

Methods

(eq) other -> Bool

Compares two instants.

Parameters

NameTypeDescription
other Value

(lt) other -> Bool

Orders two instants.

Parameters

NameTypeDescription
other DateTime

(str)() -> Str

Returns the RFC 3339 representation, as rfc does.

(sub) other -> Duration

Returns the Duration from other to this instant.

Parameters

NameTypeDescription
other DateTime Instant to subtract.

Example

let elapsed = (finish - start)
echo $elapsed.secs

date() -> Date

Returns the UTC calendar date.

rfc() -> Str

Returns the RFC 3339 representation, in UTC.

Example

let dt = DateTime.from_unix(1700000000)
echo $dt.rfc()