Skip to main content
Version: 2.x(alpha)

Datetimes

SurrealDB has native support for datetimes with nanosecond precision. SurrealDB automatically parses and understands datetimes which are written as strings in the SurrealQL language. Times must also be formatted in an ISO-8601 format.

CREATE event SET time = "2023-07-03T07:18:52Z";

SurrealDB handles all datetimes with nanosecond precision.

CREATE event SET time = "2023-07-03T07:18:52.841147Z";

SurrealDB handles all timezones, and automatically converts and stores datetimes as a UTC date.

CREATE event SET time = "2023-07-03T07:18:52.841147+02:00";

The above queries will all work even if the datetime format is incorrect, but will generate a string instead of a datetime. Casting with <datetime> will force an error if the input is incorrect.

With correct input:

CREATE event SET time = <datetime>"2023-07-03T07:18:52.841147Z";
Response
[
{
"id": "event:0ucwynrgada73ixvllxv",
"time": "2023-07-03T07:18:52.841147Z"
}
]

With incorrect input (missing final Z):

CREATE event SET time = <datetime>"2023-07-03T07:18:52.841147";
Response
"Expected a datetime but cannot convert '2023-07-03T07:18:52.841147' into a datetime"

Note: As a convenience, a date without time will always parse correctly as a datetime.

CREATE event SET time = <datetime>"2024-04-03";
Response
"2024-03-04T00:00:00Z"

Defining a schemafull table will also ensure that datetimes are properly formatted and not passed on as simple strings.

DEFINE TABLE event SCHEMAFULL;
DEFINE FIELD time ON event TYPE datetime;
CREATE event SET time = "2023-07-03T07:18:52.841147";
Response
"Found '2023-07-03T07:18:52.841147' for field `time`, with record `event:l4q1s7hermg9yoemkqrp`, but expected a datetime"

Datetime comparison

A datetime can be compared with another using the advanced SurrealDB operators.

SELECT * FROM "2023-07-03T07:18:52Z" > "2023-01-03T01:42:78Z";

Durations and datetimes

Durations can be used to modify and alter datetimes.

CREATE event SET time = "2023-07-03T07:18:52Z" + 2w;

Multi-part durations can also be used to modify datetimes.

CREATE event SET time = "2023-07-03T07:18:52.841147Z" + 1h30m20s1350ms;

Duration units

Durations can be specified in any of the following units:

UnitDescription
nsNanoseconds
usMicroseconds, alternative: µs
msMilliseconds
sSeconds
mMinutes
hHours
dDays
wWeeks
yYears

Next steps

You've now seen how to store, modify, and handle dates and times in SurrealDB. For more advanced functionality, take a look at the time functions, which enable extracting, altering, rounding, and grouping datetimes into specific time intervals.