• Start

Languages

/

JavaScript

/

API Reference

/

Data Types

DateTime

Datetime values with nanosecond precision for time-based operations.

The DateTime class provides datetime values with nanosecond precision, extending the abstract Value class to match SurrealDB's datetime type.

Import:

import { DateTime } from 'surrealdb';

Source: value/datetime.ts

Create a new datetime value.

Syntax

new DateTime() // Current time
new DateTime(datetime) // Clone existing
new DateTime(date) // From JavaScript Date
new DateTime(string) // Parse ISO string
new DateTime(number | bigint) // From timestamp
new DateTime([seconds, nanoseconds]) // From tuple
ParameterTypeDescription
value DateTime | Date | string | number | bigint | [bigint, bigint]Value to create datetime from. If omitted, uses current time.
// Current time
const now = new DateTime();

// From JavaScript Date
const date = new DateTime(new Date());

// Parse ISO string
const parsed = new DateTime('2024-01-15T12:00:00Z');

// From Unix timestamp (seconds)
const fromTimestamp = new DateTime(1705320000);

// From tuple [seconds, nanoseconds]
const precise = new DateTime([1705320000n, 500000000n]);

// Clone existing
const clone = new DateTime(now);

Get the current datetime with nanosecond precision.

Syntax

DateTime.now()

DateTime - Current datetime

const now = DateTime.now();
console.log(now.toString()); // '2024-01-15T12:30:45.123456789Z'

// Use in queries
await db.create(new Table('events')).content({
name: 'Meeting',
timestamp: DateTime.now()
});

Returns a DateTime representing the Unix epoch (1970-01-01T00:00:00Z).

Syntax

DateTime.epoch()

DateTime - Unix epoch datetime

const epoch = DateTime.epoch();
console.log(epoch.toString()); // '1970-01-01T00:00:00.000000000Z'
console.log(epoch.seconds); // 0

Create a DateTime from a nanosecond timestamp since Unix epoch.

Syntax

DateTime.fromEpochNanoseconds(ns)
ParameterTypeDescription
ns number | bigintNanoseconds since Unix epoch.

DateTime - Datetime from the nanosecond timestamp

const dt = DateTime.fromEpochNanoseconds(1705320000123456789n);
console.log(dt.toString()); // '2024-01-15T12:00:00.123456789Z'

Create a DateTime from a microsecond timestamp since Unix epoch.

Syntax

DateTime.fromEpochMicroseconds(µs)
ParameterTypeDescription
µs number | bigintMicroseconds since Unix epoch.

DateTime - Datetime from the microsecond timestamp

const dt = DateTime.fromEpochMicroseconds(1705320000123456n);
console.log(dt.toString()); // '2024-01-15T12:00:00.123456000Z'

Create a DateTime from a millisecond timestamp since Unix epoch.

Syntax

DateTime.fromEpochMilliseconds(ms)
ParameterTypeDescription
ms number | bigintMilliseconds since Unix epoch.

DateTime - Datetime from the millisecond timestamp

const dt = DateTime.fromEpochMilliseconds(1705320000123);
console.log(dt.toString()); // '2024-01-15T12:00:00.123000000Z'

Create a DateTime from a second timestamp since Unix epoch.

Syntax

DateTime.fromEpochSeconds(s)
ParameterTypeDescription
s number | bigintSeconds since Unix epoch.

DateTime - Datetime from the second timestamp

const dt = DateTime.fromEpochSeconds(1705320000);
console.log(dt.toString()); // '2024-01-15T12:00:00.000000000Z'

Convert to JavaScript Date object.

Syntax

datetime.toDate()

Date - JavaScript Date (millisecond precision)

const dt = DateTime.now();
const jsDate = dt.toDate();

// Use with JavaScript APIs
const formatted = jsDate.toLocaleDateString();

// Access Date component methods via .toDate()
console.log(jsDate.getFullYear()); // 2024
console.log(jsDate.getMonth()); // 0 (January)
console.log(jsDate.getDate()); // 15
console.log(jsDate.getHours()); // 12
console.log(jsDate.getMinutes()); // 30
console.log(jsDate.getSeconds()); // 45

Convert to ISO 8601 string with full nanosecond precision.

Syntax

datetime.toString()

string - ISO 8601 formatted string

const dt = DateTime.now();
console.log(dt.toString());
// '2024-01-15T12:30:45.123456789Z'

Convert to ISO 8601 string (alias for .toString()).

Syntax

datetime.toISOString()

string - ISO 8601 formatted string

Serialize for JSON.

Syntax

datetime.toJSON()

string - ISO string for JSON serialization

const dt = DateTime.now();
console.log(JSON.stringify({ timestamp: dt }));
// {"timestamp":"2024-01-15T12:30:45.123456789Z"}

Returns the datetime as a compact tuple of seconds and nanoseconds since Unix epoch.

Syntax

datetime.toCompact()

[bigint, bigint] - Tuple of [seconds, nanoseconds]

const dt = new DateTime('2024-01-15T12:00:00.500000000Z');
const [secs, nanos] = dt.toCompact();
console.log(secs); // 1705320000n
console.log(nanos); // 500000000n

// Round-trip via constructor
const restored = new DateTime([secs, nanos]);
console.log(dt.equals(restored)); // true

Add a duration to the datetime.

Syntax

datetime.add(duration)
ParameterTypeDescription
duration DurationDuration to add.

DateTime - New datetime with duration added

import { Duration } from 'surrealdb';

const now = DateTime.now();
const later = now.add(Duration.parse('1h30m'));
const tomorrow = now.add(Duration.parse('24h'));

Subtract a duration from the datetime.

Syntax

datetime.sub(duration)
ParameterTypeDescription
duration DurationDuration to subtract.

DateTime - New datetime with duration subtracted

const now = DateTime.now();
const earlier = now.sub(Duration.parse('1h'));
const yesterday = now.sub(Duration.parse('24h'));

Calculate the duration between two datetimes.

Syntax

datetime.diff(other)
ParameterTypeDescription
other DateTimeThe other datetime to calculate the difference from.

Duration - Duration between the two datetimes

const start = new DateTime('2024-01-15T12:00:00Z');
const end = new DateTime('2024-01-15T14:30:00Z');

const elapsed = end.diff(start);
console.log(elapsed.toString()); // '2h30m'

Compare two datetimes for ordering.

Syntax

datetime.compare(other)
ParameterTypeDescription
other DateTimeThe datetime to compare against.

number - Returns -1 if this datetime is before other, 0 if equal, 1 if after

const a = new DateTime('2024-01-15T12:00:00Z');
const b = new DateTime('2024-01-16T12:00:00Z');

console.log(a.compare(b)); // -1
console.log(b.compare(a)); // 1
console.log(a.compare(a)); // 0

// Useful for sorting
const dates = [b, a];
dates.sort((x, y) => x.compare(y));

Check if two datetimes are equal (including nanosecond precision).

Syntax

datetime.equals(other)

boolean - True if equal

Total nanoseconds since Unix epoch.

Type: bigint

const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.nanoseconds); // 1705320000123456789n

Total microseconds since Unix epoch.

Type: bigint

const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.microseconds); // 1705320000123456n

Total milliseconds since Unix epoch.

Type: number

const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.milliseconds); // 1705320000123

Seconds since Unix epoch.

Type: number

const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.seconds); // 1705320000
import { Surreal, DateTime, Table } from 'surrealdb';

const db = new Surreal();
await db.connect('ws://localhost:8000');

// Create event with timestamp
const event = await db.create(new Table('events')).content({
name: 'User Login',
user: new RecordId('users', 'john'),
timestamp: DateTime.now(),
ip: '192.168.1.1'
});

console.log('Event created at:', event.timestamp.toString());
import { DateTime, Duration } from 'surrealdb';

const now = DateTime.now();

// Add time
const future = now.add(Duration.parse('7d')); // One week later
const meeting = now.add(Duration.parse('2h30m')); // Meeting in 2.5 hours

// Subtract time
const past = now.sub(Duration.parse('30d')); // 30 days ago
const recentCutoff = now.sub(Duration.parse('1h')); // Last hour
const startDate = new DateTime('2024-01-01T00:00:00Z');
const endDate = new DateTime('2024-12-31T23:59:59Z');

const events = await db.query(`
SELECT * FROM events
WHERE timestamp >= $start AND timestamp <= $end
`, {
start: startDate,
end: endDate
}).collect();
// Record metrics with precise timestamps
async function recordMetric(name: string, value: number) {
await db.create(new Table('metrics')).content({
name,
value,
timestamp: DateTime.now()
});
}

await recordMetric('cpu_usage', 45.2);
await recordMetric('memory_usage', 78.1);

// Query recent metrics
const recent = await db.query(`
SELECT * FROM metrics
WHERE timestamp > $cutoff
ORDER BY timestamp DESC
`, {
cutoff: DateTime.now().sub(Duration.parse('5m'))
}).collect();
// From JavaScript Date
const jsDate = new Date('2024-01-15T12:00:00Z');
const dt = new DateTime(jsDate);

// To JavaScript Date
const backToJS = dt.toDate();

// From Unix timestamp
const fromTimestamp = new DateTime(1705320000);

// Get Unix timestamp in milliseconds
const timestamp = dt.milliseconds;

// Parse from string
const parsed = new DateTime('2024-01-15T12:00:00.123456789Z');

// Convert to string
const isoString = dt.toString();

// From epoch helpers
const fromNs = DateTime.fromEpochNanoseconds(1705320000123456789n);
const fromMs = DateTime.fromEpochMilliseconds(1705320000123);
const fromSecs = DateTime.fromEpochSeconds(1705320000);
// Schedule future task
const scheduledFor = DateTime.now().add(Duration.parse('1h'));

await db.create(new Table('tasks')).content({
name: 'Send reminder',
scheduled_for: scheduledFor,
status: 'pending'
});

// Find overdue tasks
const now = DateTime.now();
const overdue = await db.query(`
SELECT * FROM tasks
WHERE scheduled_for < $now
AND status = 'pending'
`, { now }).collect();
// Set expiration time
const session = await db.create(new Table('sessions')).content({
user: userId,
created_at: DateTime.now(),
expires_at: DateTime.now().add(Duration.parse('24h'))
});

// Check if expired
function isExpired(expiresAt: DateTime): boolean {
return DateTime.now().milliseconds > expiresAt.milliseconds;
}

if (isExpired(session.expires_at)) {
await db.delete(session.id);
}
// DateTime is always stored in UTC
const utcTime = DateTime.now();

// Convert to local time for display
const localDate = utcTime.toDate();
const localString = localDate.toLocaleString();

console.log('UTC:', utcTime.toString());
console.log('Local:', localString);
// Good: Nanosecond precision preserved
await db.create(new Table('logs')).content({
timestamp: DateTime.now(),
message: 'Event occurred'
});

// Avoid: JavaScript Date (millisecond precision only)
await db.create(new Table('logs')).content({
timestamp: new Date(),
message: 'Event occurred'
});
// Good: Keep as DateTime for precision
const dt = DateTime.now();
const stored = dt.toString(); // Preserves nanoseconds

// Caution: Loses nanosecond precision
const jsDate = dt.toDate(); // Only milliseconds
// Good: Type-safe duration arithmetic
const future = now.add(Duration.parse('1h'));

// Avoid: Manual millisecond math
const future2 = DateTime.fromEpochMilliseconds(now.milliseconds + 3600000);
// Store in UTC using DateTime
const timestamp = DateTime.now();
await db.create(table).content({ created_at: timestamp });

// Display in user's timezone
const localDisplay = timestamp.toDate().toLocaleString('en-US', {
timeZone: 'America/New_York'
});

Was this page helpful?