The 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 tupleParameters
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.nanoseconds(ns)
Create a duration from a number of nanoseconds.
Duration.nanoseconds(ns)Parameters
Parameter | Type | Description |
|---|---|---|
ns | number | bigint | Number of nanoseconds. |
Returns
Duration - Duration representing the given nanoseconds
Example
const d = Duration.nanoseconds(500); Duration.microseconds(µs)
Create a duration from a number of microseconds.
Duration.microseconds(µs)Parameters
Parameter | Type | Description |
|---|---|---|
µs | number | bigint | Number of microseconds. |
Returns
Duration - Duration representing the given microseconds
Example
const d = Duration.microseconds(250); Duration.milliseconds(ms)
Create a duration from a number of milliseconds.
Duration.milliseconds(ms)Parameters
Parameter | Type | Description |
|---|---|---|
ms | number | bigint | Number of milliseconds. |
Returns
Duration - Duration representing the given milliseconds
Example
const d = Duration.milliseconds(1500);
console.log(d.toString()); // '1s500ms' Duration.seconds(s)
Create a duration from a number of seconds.
Duration.seconds(s)Parameters
Parameter | Type | Description |
|---|---|---|
s | number | bigint | Number of seconds. |
Returns
Duration - Duration representing the given seconds
Example
const d = Duration.seconds(90);
console.log(d.toString()); // '1m30s' Duration.minutes(m)
Create a duration from a number of minutes.
Duration.minutes(m)Parameters
Parameter | Type | Description |
|---|---|---|
m | number | bigint | Number of minutes. |
Returns
Duration - Duration representing the given minutes
Example
const d = Duration.minutes(5);
console.log(d.toString()); // '5m' Duration.hours(h)
Create a duration from a number of hours.
Duration.hours(h)Parameters
Parameter | Type | Description |
|---|---|---|
h | number | bigint | Number of hours. |
Returns
Duration - Duration representing the given hours
Example
const d = Duration.hours(2);
console.log(d.toString()); // '2h' Duration.days(d)
Create a duration from a number of days.
Duration.days(d)Parameters
Parameter | Type | Description |
|---|---|---|
d | number | bigint | Number of days. |
Returns
Duration - Duration representing the given days
Example
const d = Duration.days(7);
console.log(d.toString()); // '1w' Duration.weeks(w)
Create a duration from a number of weeks.
Duration.weeks(w)Parameters
Parameter | Type | Description |
|---|---|---|
w | number | bigint | Number of weeks. |
Returns
Duration - Duration representing the given weeks
Example
const d = Duration.weeks(4);
console.log(d.toString()); // '4w' Duration.years(y)
Create a duration from a number of years.
Duration.years(y)Parameters
Parameter | Type | Description |
|---|---|---|
y | number | bigint | Number of years. |
Returns
Duration - Duration representing the given years
Example
const d = Duration.years(1);
console.log(d.toString()); // '1y' Duration.parseFloat(input)
Parse a duration from a float string with a unit suffix.
Duration.parseFloat(input)Parameters
Parameter | Type | Description |
|---|---|---|
input | string | A float string with a unit suffix (e.g., "1.5s"). |
Returns
Duration - Parsed duration
Example
const d = Duration.parseFloat('1.5s');
console.log(d.milliseconds); // 1500n Duration.measure()
Returns a function that, when called, returns the elapsed Duration since the call to Duration.measure().
Duration.measure()Returns
() => Duration - A function that returns the elapsed duration
Example
const elapsed = Duration.measure();
// ... perform some operation ...
const duration = elapsed();
console.log('Operation took:', duration.toString());Property getters
Property getters for accessing the total duration in specific units. All return bigint.
Property | Type | Description |
|---|---|---|
nanoseconds | bigint | Total nanoseconds |
microseconds | bigint | Total microseconds |
milliseconds | bigint | Total milliseconds |
seconds | bigint | Whole seconds |
minutes | bigint | Total whole minutes |
hours | bigint | Total whole hours |
days | bigint | Total whole days |
weeks | bigint | Total whole weeks |
years | bigint | Total whole years |
Examples
const duration = new Duration('2h30m');
console.log(duration.hours); // 2n
console.log(duration.minutes); // 150n
console.log(duration.seconds); // 9000n
console.log(duration.milliseconds); // 9000000n
console.log(duration.nanoseconds); // 9000000000000nInstance methods
.toString()
Convert to human-readable string.
duration.toString()Returns
string - Human-readable duration string
Example
const duration = new Duration('2h30m15s');
console.log(duration.toString()); // '2h30m15s' .toJSON()
Serialize for JSON.
duration.toJSON()Returns
string - Duration string for JSON
.toCompact()
Convert to a compact tuple representation.
duration.toCompact()Returns
[bigint, bigint] | [bigint] | [] - Compact representation: [seconds, nanoseconds], [seconds] if nanoseconds is zero, or [] for a zero duration.
Example
const d = new Duration('5m30s');
console.log(d.toCompact()); // [330n, 0n] or [330n] .add(other)
Add another duration.
duration.add(other)Parameters
Parameter | Type | Description |
|---|---|---|
other | Duration | Duration to add. |
Returns
Duration - Sum of durations
Example
const base = new Duration('1h');
const extra = new Duration('30m');
const total = base.add(extra);
console.log(total.toString()); // '1h30m' .sub(other)
Subtract another duration.
duration.sub(other)Parameters
Parameter | Type | Description |
|---|---|---|
other | Duration | Duration to subtract. |
Returns
Duration - Difference of durations
Example
const total = new Duration('2h');
const part = new Duration('30m');
const remaining = total.sub(part);
console.log(remaining.toString()); // '1h30m' .mul(factor)
Multiply a duration by a scalar.
duration.mul(factor)Parameters
Parameter | Type | Description |
|---|---|---|
factor | number | bigint | Scalar to multiply by. |
Returns
Duration - Scaled duration
Example
const base = new Duration('30m');
const doubled = base.mul(2);
console.log(doubled.toString()); // '1h' .div(divisor)
Divide a duration. Overloaded: dividing by a Duration returns the ratio as bigint, dividing by a number returns a new Duration.
duration.div(divisor: Duration) // Returns bigint (ratio)
duration.div(divisor: number | bigint) // Returns DurationParameters
Parameter | Type | Description |
|---|---|---|
divisor | Duration | number | bigint | Duration for ratio, or scalar for division. |
Returns
bigint when dividing by a Duration, Duration when dividing by a number or bigint.
Examples
const total = new Duration('2h');
const unit = new Duration('30m');
// Ratio: how many 30m intervals in 2h?
const ratio = total.div(unit); // 4n
// Scalar division
const half = total.div(2);
console.log(half.toString()); // '1h' .mod(mod)
Get the remainder after dividing by another duration.
duration.mod(mod)Parameters
Parameter | Type | Description |
|---|---|---|
mod | Duration | Duration to divide by. |
Returns
Duration - Remainder after division
Example
const total = new Duration('2h20m');
const interval = new Duration('1h');
const remainder = total.mod(interval);
console.log(remainder.toString()); // '20m' .equals(other)
Check if two durations are equal.
duration.equals(other)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: new Duration('24h')
});Query timeouts
// Set timeout on queries
const users = await db.select(new Table('users'))
.timeout(new Duration('5s'));
// Timeout on complex query
const result = await db.query(`
SELECT * FROM complex_view
`).timeout(new Duration('30s')).collect();Rate limiting
// Define rate limit window
const rateLimit = {
window: new Duration('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: new Duration('5m'),
created_at: DateTime.now()
});Cache TTL
// Set cache entry with TTL
const cacheEntry = await db.create(new Table('cache')).content({
key: 'user:123',
value: userData,
ttl: new Duration('1h'),
cached_at: DateTime.now()
});
// Check if cache is still valid
function isCacheValid(entry: typeof cacheEntry): boolean {
const elapsed = DateTime.now().milliseconds - entry.cached_at.milliseconds;
return elapsed < entry.ttl.milliseconds;
}Performance measurement
// Measure operation duration
const elapsed = Duration.measure();
// ... perform operation ...
const duration = elapsed();
console.log('Operation took:', duration.toString());Conversion examples
// Parse from string
const duration = new Duration('2h30m');
// Access as different units
const ms = duration.milliseconds; // 9000000n
const secs = duration.seconds; // 9000n
const mins = duration.minutes; // 150n
const hrs = duration.hours; // 2n
// Back to string
const str = duration.toString(); // '2h30m'
// Arithmetic
const doubled = duration.add(duration);
console.log(doubled.toString()); // '5h'Complex durations
// Very precise timing
const precise = new Duration('1s500ms250us125ns');
// Multiple units
const complex = new Duration('1d2h30m15s');
// Arithmetic
const extended = complex.add(new Duration('12h'));
console.log(extended.toString()); // '1d14h30m15s'Static factory methods
// Create durations from numeric values
const timeout = Duration.seconds(30);
const cacheTTL = Duration.hours(1);
const retryDelay = Duration.milliseconds(500);
const oneWeek = Duration.weeks(1);
// Useful when values come from config or computation
const maxRetries = 3;
const backoff = Duration.seconds(2).mul(maxRetries);Best practices
1. Use human-readable formats
// Good: Clear intent
const timeout = new Duration('30s');
const cacheTTL = new Duration('1h');
// Avoid: Raw numbers
const timeout = new Duration([30n, 0n]);2. Use Duration for time arithmetic
// Good: Type-safe duration arithmetic
const base = new Duration('1h');
const extended = base.add(new Duration('30m'));
// Good: Use static factories for computed values
const delay = Duration.seconds(retryCount * 2);3. Store durations in database
// Good: Store as Duration for type safety
await db.create(table).content({
timeout: new Duration('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 = new Duration('1d');
const oneWeek = new Duration('1w');
// Avoid: Unnecessary smaller units
const oneDay = new Duration('24h');
const oneWeek = new Duration('168h');5. Use duration.measure() for timing
// Good: Built-in measurement
const elapsed = Duration.measure();
await performOperation();
console.log('Took:', elapsed().toString());See also
DateTime - Datetime values
Data types overview - All custom data types
Query builders - Using Duration in queries
SurrealQL durations - Database duration type