DurationThe Duration class provides time duration values with nanosecond precision and support for human-readable formats like "5h30m".
Import:
import { Duration } from 'surrealdb' ; Source: value/duration.ts
Constructor new Duration(value)Create a new duration value.
new Duration ( duration ) // Clone existing new Duration ( string ) // Parse human-readable string new Duration ( [ seconds , nanoseconds ] ) // From tuple Parameters Parameter Type Description value Duration | string | [bigint, bigint]Value to create duration from.
Examples // Parse human-readable durations const fiveMinutes = new Duration ( '5m' ) ; const oneHour = new Duration ( '1h' ) ; const complex = new Duration ( '2h30m15s' ) ; const precise = new Duration ( '1s500ms250us125ns' ) ; // From tuple [seconds, nanoseconds] const duration = new Duration ( [ 300n , 0n ] ) ; // 5 minutes // Clone existing const clone = new Duration ( fiveMinutes ) ; Supported Units Unit Symbol Example Nanoseconds ns"500ns"Microseconds us, µs"250us"Milliseconds ms"100ms"Seconds s"30s"Minutes m"5m"Hours h"2h"Days d"7d"Weeks w"4w"Years y"1y"
Static Methods Duration.parse(string)Parse a duration from a human-readable string.
Parameters Parameter Type Description str stringDuration string (e.g., "5h30m").
Returns Duration - Parsed duration
Examples // Simple durations const fiveMinutes = Duration . parse ( '5m' ) ; const oneHour = Duration . parse ( '1h' ) ; const oneDay = Duration . parse ( '1d' ) ; // Combined units const sessionTimeout = Duration . parse ( '2h30m' ) ; const cacheExpiry = Duration . parse ( '1d12h' ) ; const precise = Duration . parse ( '1h30m45s500ms' ) ; // Very precise const measurement = Duration . parse ( '1s250ms500us750ns' ) ; Instance Methods .toMilliseconds()Convert duration to milliseconds.
duration . toMilliseconds ( ) Returns number - Duration in milliseconds
Example const duration = Duration . parse ( '5m30s' ) ; console . log ( duration . toMilliseconds ( ) ) ; // 330000
.toSeconds()Convert duration to seconds.
Returns number - Duration in seconds
Example const duration = Duration . parse ( '2h30m' ) ; console . log ( duration . toSeconds ( ) ) ; // 9000
.toString()Convert to human-readable string.
Returns string - Human-readable duration string
Example const duration = Duration . parse ( '2h30m15s' ) ; console . log ( duration . toString ( ) ) ; // '2h30m15s'
.toJSON()Serialize for JSON.
Returns string - Duration string for JSON
.plus(duration)Add another duration.
Parameters Parameter Type Description other DurationDuration to add.
Returns Duration - Sum of durations
Example const base = Duration . parse ( '1h' ) ; const extra = Duration . parse ( '30m' ) ; const total = base . plus ( extra ) ; console . log ( total . toString ( ) ) ; // '1h30m'
.minus(duration)Subtract another duration.
Returns Duration - Difference of durations
.equals(other)Check if two durations are equal.
Returns boolean - True if equal
Complete Examples Timeouts and Expiration import { Surreal , Duration , DateTime , Table } from 'surrealdb' ; const db = new Surreal ( ) ; await db . connect ( 'ws://localhost:8000' ) ; // Set session timeout const session = await db . create ( new Table ( 'sessions' ) ) . content ( { user : userId , created_at : DateTime . now ( ) , timeout : Duration . parse ( '24h' ) } ) ; // Calculate expiration const expiresAt = session . created_at . plus ( session . timeout ) ; Query Timeouts // Set timeout on queries const users = await db . select ( new Table ( 'users' ) ) . timeout ( Duration . parse ( '5s' ) ) ; // Timeout on complex query const result = await db . query ( ` SELECT * FROM complex_view ` ) . timeout ( Duration . parse ( '30s' ) ) . collect ( ) ; Rate Limiting // Define rate limit window const rateLimit = { window : Duration . parse ( '1m' ) , maxRequests : 100 } ; // Store rate limit data await db . create ( new Table ( 'rate_limits' ) ) . content ( { user : userId , window : rateLimit . window , requests : 1 , window_start : DateTime . now ( ) } ) ; Scheduled Tasks // Schedule task with delay const task = await db . create ( new Table ( 'tasks' ) ) . content ( { name : 'Send email' , delay : Duration . parse ( '5m' ) , created_at : DateTime . now ( ) } ) ; // Calculate execution time const executeAt = task . created_at . plus ( task . delay ) ; console . log ( 'Execute at:' , executeAt . toString ( ) ) ; Cache TTL // Set cache entry with TTL const cacheEntry = await db . create ( new Table ( 'cache' ) ) . content ( { key : 'user:123' , value : userData , ttl : Duration . parse ( '1h' ) , cached_at : DateTime . now ( ) } ) ; // Check if cache is still valid function isCacheValid ( entry : typeof cacheEntry ) : boolean { const expiresAt = entry . cached_at . plus ( entry . ttl ) ; return DateTime . now ( ) . getTime ( ) < expiresAt . getTime ( ) ; } // Measure operation duration const start = DateTime . now ( ) ; // ... perform operation ... const end = DateTime . now ( ) ; const elapsed = Duration . parse ( ` ${ end . getTime ( ) - start . getTime ( ) } ms` ) ; console . log ( 'Operation took:' , elapsed . toString ( ) ) ; Conversion Examples // Parse from string const duration = Duration . parse ( '2h30m' ) ; // Convert to milliseconds const ms = duration . toMilliseconds ( ) ; // 9000000 // Convert to seconds const seconds = duration . toSeconds ( ) ; // 9000 // Back to string const str = duration . toString ( ) ; // '2h30m' // Arithmetic const doubled = duration . plus ( duration ) ; console . log ( doubled . toString ( ) ) ; // '5h' Complex Durations // Very precise timing const precise = Duration . parse ( '1s500ms250us125ns' ) ; // Multiple units const complex = Duration . parse ( '1d2h30m15s' ) ; // Arithmetic const extended = complex . plus ( Duration . parse ( '12h' ) ) ; console . log ( extended . toString ( ) ) ; // '1d14h30m15s' Best Practices // Good: Clear intent const timeout = Duration . parse ( '30s' ) ; const cacheTTL = Duration . parse ( '1h' ) ; // Avoid: Raw numbers const timeout = new Duration ( [ 30n , 0n ] ) ; 2. Use Duration for Time Arithmetic // Good: Type-safe duration arithmetic const now = DateTime . now ( ) ; const future = now . plus ( Duration . parse ( '1h' ) ) ; // Avoid: Manual millisecond math const future = new DateTime ( now . getTime ( ) + 3600000 ) ; 3. Store Durations in Database // Good: Store as Duration for type safety await db . create ( table ) . content ( { timeout : Duration . parse ( '24h' ) } ) ; // Avoid: Store as number await db . create ( table ) . content ( { timeout : 86400000 // What unit is this? } ) ; 4. Use Appropriate Units // Good: Use largest appropriate unit const oneDay = Duration . parse ( '1d' ) ; const oneWeek = Duration . parse ( '1w' ) ; // Avoid: Unnecessary smaller units const oneDay = Duration . parse ( '24h' ) ; const oneWeek = Duration . parse ( '168h' ) ; See Also