DateTimeThe 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
new DateTime(value?)Create a new datetime value.
Syntaxnew 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
| Parameter | Type | Description |
|---|---|---|
value optional | 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);
DateTime.now()Get the current datetime with nanosecond precision.
SyntaxDateTime.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() });
DateTime.parse(string)Parse a datetime from an ISO 8601 string.
SyntaxDateTime.parse(str)
| Parameter | Type | Description |
|---|---|---|
str required | string | ISO 8601 formatted string. |
DateTime - Parsed datetime
// 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');
.toDate()Convert to JavaScript Date object.
Syntaxdatetime.toDate()
Date - JavaScript Date (millisecond precision)
WarningJavaScript Date only supports millisecond precision. Nanosecond precision is lost in conversion.
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.
Syntaxdatetime.toString()
string - ISO 8601 formatted string
const dt = DateTime.now(); console.log(dt.toString()); // '2024-01-15T12:30:45.123456789Z'
.toISOString()Convert to ISO 8601 string (alias for .toString()).
Syntaxdatetime.toISOString()
string - ISO 8601 formatted string
.toJSON()Serialize for JSON.
Syntaxdatetime.toJSON()
string - ISO string for JSON serialization
const dt = DateTime.now(); console.log(JSON.stringify({ timestamp: dt })); // {"timestamp":"2024-01-15T12:30:45.123456789Z"}
.getTime()Get Unix timestamp in milliseconds.
Syntaxdatetime.getTime()
number - Milliseconds since Unix epoch
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)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.
Syntaxdatetime.plus(duration)
| Parameter | Type | Description |
|---|---|---|
duration required | Duration | Duration to add. |
DateTime - New datetime with duration added
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.
Syntaxdatetime.minus(duration)
| Parameter | Type | Description |
|---|---|---|
duration required | Duration | Duration to subtract. |
DateTime - New datetime with duration subtracted
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).
Syntaxdatetime.equals(other)
boolean - True if equal
nanosecondsThe nanosecond component (0-999999999).
Type: bigint
const dt = DateTime.parse('2024-01-15T12:00:00.123456789Z'); console.log(dt.nanoseconds); // 123456789n
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.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
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();
// 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();
// 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();
// 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();
// 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); }
// 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.plus(Duration.parse('1h')); // Avoid: Manual millisecond math const future = new DateTime(now.getTime() + 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' });