DateTime

The DateTime class provides datetime values with nanosecond precision, extending JavaScript's Date capabilities to match SurrealDB's datetime type.

Import:

import { DateTime } from 'surrealdb';

Source: value/datetime.ts

Constructor

new DateTime(value?)

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

Parameters

ParameterTypeDescription
value DateTime | Date | string | number | bigint | [bigint, bigint]Value to create datetime from. If omitted, uses current time.

Examples

// 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);

Static Methods

DateTime.now()

Get the current datetime with nanosecond precision.

Syntax

DateTime.now()

Returns

DateTime - Current datetime

Example

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()
});

DateTime.parse(string)

Parse a datetime from an ISO 8601 string.

Syntax

DateTime.parse(str)

Parameters

ParameterTypeDescription
str stringISO 8601 formatted string.

Returns

DateTime - Parsed datetime

Examples

// Standard ISO format
const dt1 = DateTime.parse('2024-01-15T12:00:00Z');

// With milliseconds
const dt2 = DateTime.parse('2024-01-15T12:00:00.123Z');

// With microseconds
const dt3 = DateTime.parse('2024-01-15T12:00:00.123456Z');

// With nanoseconds (full precision)
const dt4 = DateTime.parse('2024-01-15T12:00:00.123456789Z');

Instance Methods

.toDate()

Convert to JavaScript Date object.

Syntax

datetime.toDate()

Returns

Date - JavaScript Date (millisecond precision)

Example

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

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

.toString()

Convert to ISO 8601 string with full nanosecond precision.

Syntax

datetime.toString()

Returns

string - ISO 8601 formatted string

Example

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

.toISOString()

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

Syntax

datetime.toISOString()

Returns

string - ISO 8601 formatted string

.toJSON()

Serialize for JSON.

Syntax

datetime.toJSON()

Returns

string - ISO string for JSON serialization

Example

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

.getTime()

Get Unix timestamp in milliseconds.

Syntax

datetime.getTime()

Returns

number - Milliseconds since Unix epoch

Example

const dt = DateTime.now();
const ms = dt.getTime();
console.log(ms); // 1705320645123

.getFullYear(), .getMonth(), .getDate(), etc.

Get individual datetime components.

Available Methods:

  • .getFullYear() - Year (e.g., 2024)

  • .getMonth() - Month (0-11, where 0 = January)

  • .getDate() - Day of month (1-31)

  • .getDay() - Day of week (0-6, where 0 = Sunday)

  • .getHours() - Hours (0-23)

  • .getMinutes() - Minutes (0-59)

  • .getSeconds() - Seconds (0-59)

  • .getMilliseconds() - Milliseconds (0-999)

Example

const dt = DateTime.parse('2024-01-15T12:30:45.123Z');

console.log(dt.getFullYear()); // 2024
console.log(dt.getMonth()); // 0 (January)
console.log(dt.getDate()); // 15
console.log(dt.getHours()); // 12
console.log(dt.getMinutes()); // 30
console.log(dt.getSeconds()); // 45

.plus(duration)

Add a duration to the datetime.

Syntax

datetime.plus(duration)

Parameters

ParameterTypeDescription
duration DurationDuration to add.

Returns

DateTime - New datetime with duration added

Example

import { Duration } from 'surrealdb';

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

.minus(duration)

Subtract a duration from the datetime.

Syntax

datetime.minus(duration)

Parameters

ParameterTypeDescription
duration DurationDuration to subtract.

Returns

DateTime - New datetime with duration subtracted

Example

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

.equals(other)

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

Syntax

datetime.equals(other)

Returns

boolean - True if equal

Properties

nanoseconds

The nanosecond component (0-999999999).

Type: bigint

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

Complete Examples

Event Timestamps

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());

Date Arithmetic

import { DateTime, Duration } from 'surrealdb';

const now = DateTime.now();

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

// Subtract time
const past = now.minus(Duration.parse('30d')); // 30 days ago
const recentCutoff = now.minus(Duration.parse('1h')); // Last hour

Query with Date Ranges

const startDate = DateTime.parse('2024-01-01T00:00:00Z');
const endDate = DateTime.parse('2024-12-31T23:59:59Z');

const events = await db.query(`
SELECT * FROM events
WHERE timestamp >= $start AND timestamp <= $end
`, {
start: startDate,
end: endDate
}).collect();

Time-series Data

// 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().minus(Duration.parse('5m'))
}).collect();

Conversion Examples

// 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
const timestamp = dt.getTime();

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

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

Scheduled Tasks

// Schedule future task
const scheduledFor = DateTime.now().plus(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();

Expiration Handling

// Set expiration time
const session = await db.create(new Table('sessions')).content({
user: userId,
created_at: DateTime.now(),
expires_at: DateTime.now().plus(Duration.parse('24h'))
});

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

if (isExpired(session.expires_at)) {
await db.delete(session.id);
}

Timezone Handling

// 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);

Best Practices

1. Use DateTime for Database Timestamps

// 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'
});

2. Be Aware of Precision Loss

// 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

3. Use Duration for Time Arithmetic

// Good: Type-safe duration arithmetic
const future = now.plus(Duration.parse('1h'));

// Avoid: Manual millisecond math
const future = new DateTime(now.getTime() + 3600000);

4. Store as DateTime, Display as Localized

// 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'
});

See Also