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
Constructor new DateTime(value?)Create a new datetime value.
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 Parameter Type Description 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.
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.epoch()Returns a DateTime representing the Unix epoch (1970-01-01T00:00:00Z).
Returns DateTime - Unix epoch datetime
Example const epoch = DateTime . epoch ( ) ; console . log ( epoch . toString ( ) ) ; // '1970-01-01T00:00:00.000000000Z' console . log ( epoch . seconds ) ; // 0
DateTime.fromEpochNanoseconds(ns)Create a DateTime from a nanosecond timestamp since Unix epoch.
DateTime . fromEpochNanoseconds ( ns ) Parameters Parameter Type Description ns number | bigintNanoseconds since Unix epoch.
Returns DateTime - Datetime from the nanosecond timestamp
Example const dt = DateTime . fromEpochNanoseconds ( 1705320000123456789n ) ; console . log ( dt . toString ( ) ) ; // '2024-01-15T12:00:00.123456789Z'
DateTime.fromEpochMicroseconds(µs)Create a DateTime from a microsecond timestamp since Unix epoch.
DateTime . fromEpochMicroseconds ( µs ) Parameters Parameter Type Description µs number | bigintMicroseconds since Unix epoch.
Returns DateTime - Datetime from the microsecond timestamp
Example const dt = DateTime . fromEpochMicroseconds ( 1705320000123456n ) ; console . log ( dt . toString ( ) ) ; // '2024-01-15T12:00:00.123456000Z'
DateTime.fromEpochMilliseconds(ms)Create a DateTime from a millisecond timestamp since Unix epoch.
DateTime . fromEpochMilliseconds ( ms ) Parameters Parameter Type Description ms number | bigintMilliseconds since Unix epoch.
Returns DateTime - Datetime from the millisecond timestamp
Example const dt = DateTime . fromEpochMilliseconds ( 1705320000123 ) ; console . log ( dt . toString ( ) ) ; // '2024-01-15T12:00:00.123000000Z'
DateTime.fromEpochSeconds(s)Create a DateTime from a second timestamp since Unix epoch.
DateTime . fromEpochSeconds ( s ) Parameters Parameter Type Description s number | bigintSeconds since Unix epoch.
Returns DateTime - Datetime from the second timestamp
Example const dt = DateTime . fromEpochSeconds ( 1705320000 ) ; console . log ( dt . toString ( ) ) ; // '2024-01-15T12:00:00.000000000Z' Instance Methods .toDate()Convert to JavaScript Date object.
Returns Date - JavaScript Date (millisecond precision)
JavaScript Date only supports millisecond precision. Nanosecond precision is lost in conversion.
DateTime does not extend JavaScript's Date. To use Date methods like .getFullYear(), .getMonth(), .getDate(), .getHours(), etc., first call .toDate().
Example 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
.toString()Convert to ISO 8601 string with full nanosecond precision.
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()).
Returns string - ISO 8601 formatted string
.toJSON()Serialize for JSON.
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"}
.toCompact()Returns the datetime as a compact tuple of seconds and nanoseconds since Unix epoch.
Returns [bigint, bigint] - Tuple of [seconds, nanoseconds]
Example 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(duration)Add a duration to the datetime.
Parameters Parameter Type Description duration DurationDuration to add.
Returns DateTime - New datetime with duration added
Example import { Duration } from 'surrealdb' ; const now = DateTime . now ( ) ; const later = now . add ( Duration . parse ( '1h30m' ) ) ; const tomorrow = now . add ( Duration . parse ( '24h' ) ) ;
.sub(duration)Subtract a duration from the datetime.
Parameters Parameter Type Description duration DurationDuration to subtract.
Returns DateTime - New datetime with duration subtracted
Example const now = DateTime . now ( ) ; const earlier = now . sub ( Duration . parse ( '1h' ) ) ; const yesterday = now . sub ( Duration . parse ( '24h' ) ) ;
.diff(other)Calculate the duration between two datetimes.
Parameters Parameter Type Description other DateTimeThe other datetime to calculate the difference from.
Returns Duration - Duration between the two datetimes
Example 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(other)Compare two datetimes for ordering.
Parameters Parameter Type Description other DateTimeThe datetime to compare against.
Returns number - Returns -1 if this datetime is before other, 0 if equal, 1 if after
Example 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 ) ) ;
.equals(other)Check if two datetimes are equal (including nanosecond precision).
Returns boolean - True if equal
Properties nanosecondsTotal nanoseconds since Unix epoch.
Type: bigint
const dt = new DateTime ( '2024-01-15T12:00:00.123456789Z' ) ; console . log ( dt . nanoseconds ) ; // 1705320000123456789n
microsecondsTotal microseconds since Unix epoch.
Type: bigint
const dt = new DateTime ( '2024-01-15T12:00:00.123456789Z' ) ; console . log ( dt . microseconds ) ; // 1705320000123456n
millisecondsTotal milliseconds since Unix epoch.
Type: number
const dt = new DateTime ( '2024-01-15T12:00:00.123456789Z' ) ; console . log ( dt . milliseconds ) ; // 1705320000123
secondsSeconds since Unix epoch.
Type: number
const dt = new DateTime ( '2024-01-15T12:00:00.123456789Z' ) ; console . log ( dt . seconds ) ; // 1705320000 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 . 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 Query with Date Ranges 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 ( ) ; 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 ( ) . sub ( 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 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 ) ; Scheduled Tasks // 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 ( ) ; Expiration Handling // 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 ) ; } 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 . add ( Duration . parse ( '1h' ) ) ; // Avoid: Manual millisecond math const future2 = DateTime . fromEpochMilliseconds ( now . milliseconds + 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