# Duration

Time duration values with support for multiple units and nanosecond precision.

The `Duration` class provides time duration values with nanosecond precision and support for human-readable formats like `"5h30m"`.

**Import:**
```ts
import { Duration } from 'surrealdb';
```

**Source:** [value/duration.ts](https://github.com/surrealdb/surrealdb.js/blob/main/packages/sdk/src/value/duration.ts)

## Constructor

### `new Duration(value)` {#constructor}

Create a new duration value.

```ts title="Syntax"
new Duration(duration) // Clone existing
new Duration(string) // Parse human-readable string
new Duration([seconds, nanoseconds]) // From tuple
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>value</code> <label label="required" /></td>
            <td><code>Duration | string | [bigint, bigint]</code></td>
            <td>Value to create duration from.</td>
        </tr>
    </tbody>
</table>

#### Examples

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

<table>
    <thead>
        <tr>
            <th>Unit</th>
            <th>Symbol</th>
            <th>Example</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Nanoseconds</td>
            <td><code>ns</code></td>
            <td><code>"500ns"</code></td>
        </tr>
        <tr>
            <td>Microseconds</td>
            <td><code>us</code>, <code>µs</code></td>
            <td><code>"250us"</code></td>
        </tr>
        <tr>
            <td>Milliseconds</td>
            <td><code>ms</code></td>
            <td><code>"100ms"</code></td>
        </tr>
        <tr>
            <td>Seconds</td>
            <td><code>s</code></td>
            <td><code>"30s"</code></td>
        </tr>
        <tr>
            <td>Minutes</td>
            <td><code>m</code></td>
            <td><code>"5m"</code></td>
        </tr>
        <tr>
            <td>Hours</td>
            <td><code>h</code></td>
            <td><code>"2h"</code></td>
        </tr>
        <tr>
            <td>Days</td>
            <td><code>d</code></td>
            <td><code>"7d"</code></td>
        </tr>
        <tr>
            <td>Weeks</td>
            <td><code>w</code></td>
            <td><code>"4w"</code></td>
        </tr>
        <tr>
            <td>Years</td>
            <td><code>y</code></td>
            <td><code>"1y"</code></td>
        </tr>
    </tbody>
</table>

## Static methods

### `Duration.nanoseconds(ns)` {#nanoseconds-static}

Create a duration from a number of nanoseconds.

```ts title="Syntax"
Duration.nanoseconds(ns)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ns</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of nanoseconds.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given nanoseconds

#### Example

```ts
const d = Duration.nanoseconds(500);
```

---

### `Duration.microseconds(µs)` {#microseconds-static}

Create a duration from a number of microseconds.

```ts title="Syntax"
Duration.microseconds(µs)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>µs</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of microseconds.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given microseconds

#### Example

```ts
const d = Duration.microseconds(250);
```

---

### `Duration.milliseconds(ms)` {#milliseconds-static}

Create a duration from a number of milliseconds.

```ts title="Syntax"
Duration.milliseconds(ms)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ms</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of milliseconds.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given milliseconds

#### Example

```ts
const d = Duration.milliseconds(1500);
console.log(d.toString()); // '1s500ms'
```

---

### `Duration.seconds(s)` {#seconds-static}

Create a duration from a number of seconds.

```ts title="Syntax"
Duration.seconds(s)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>s</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of seconds.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given seconds

#### Example

```ts
const d = Duration.seconds(90);
console.log(d.toString()); // '1m30s'
```

---

### `Duration.minutes(m)` {#minutes-static}

Create a duration from a number of minutes.

```ts title="Syntax"
Duration.minutes(m)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>m</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of minutes.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given minutes

#### Example

```ts
const d = Duration.minutes(5);
console.log(d.toString()); // '5m'
```

---

### `Duration.hours(h)` {#hours-static}

Create a duration from a number of hours.

```ts title="Syntax"
Duration.hours(h)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>h</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of hours.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given hours

#### Example

```ts
const d = Duration.hours(2);
console.log(d.toString()); // '2h'
```

---

### `Duration.days(d)` {#days-static}

Create a duration from a number of days.

```ts title="Syntax"
Duration.days(d)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>d</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of days.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given days

#### Example

```ts
const d = Duration.days(7);
console.log(d.toString()); // '1w'
```

---

### `Duration.weeks(w)` {#weeks-static}

Create a duration from a number of weeks.

```ts title="Syntax"
Duration.weeks(w)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>w</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of weeks.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given weeks

#### Example

```ts
const d = Duration.weeks(4);
console.log(d.toString()); // '4w'
```

---

### `Duration.years(y)` {#years-static}

Create a duration from a number of years.

```ts title="Syntax"
Duration.years(y)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>y</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Number of years.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Duration representing the given years

#### Example

```ts
const d = Duration.years(1);
console.log(d.toString()); // '1y'
```

---

### `Duration.parseFloat(input)` {#parsefloat}

Parse a duration from a float string with a unit suffix.

```ts title="Syntax"
Duration.parseFloat(input)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>input</code> <label label="required" /></td>
            <td><code>string</code></td>
            <td>A float string with a unit suffix (e.g., <code>"1.5s"</code>).</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Parsed duration

#### Example

```ts
const d = Duration.parseFloat('1.5s');
console.log(d.milliseconds); // 1500n
```

---

### `Duration.measure()` {#measure}

Returns a function that, when called, returns the elapsed `Duration` since the call to `Duration.measure()`.

```ts title="Syntax"
Duration.measure()
```

#### Returns
`() => Duration` - A function that returns the elapsed duration

#### Example

```ts
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`.

<table>
    <thead>
        <tr>
            <th>Property</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>nanoseconds</code></td>
            <td><code>bigint</code></td>
            <td>Total nanoseconds</td>
        </tr>
        <tr>
            <td><code>microseconds</code></td>
            <td><code>bigint</code></td>
            <td>Total microseconds</td>
        </tr>
        <tr>
            <td><code>milliseconds</code></td>
            <td><code>bigint</code></td>
            <td>Total milliseconds</td>
        </tr>
        <tr>
            <td><code>seconds</code></td>
            <td><code>bigint</code></td>
            <td>Whole seconds</td>
        </tr>
        <tr>
            <td><code>minutes</code></td>
            <td><code>bigint</code></td>
            <td>Total whole minutes</td>
        </tr>
        <tr>
            <td><code>hours</code></td>
            <td><code>bigint</code></td>
            <td>Total whole hours</td>
        </tr>
        <tr>
            <td><code>days</code></td>
            <td><code>bigint</code></td>
            <td>Total whole days</td>
        </tr>
        <tr>
            <td><code>weeks</code></td>
            <td><code>bigint</code></td>
            <td>Total whole weeks</td>
        </tr>
        <tr>
            <td><code>years</code></td>
            <td><code>bigint</code></td>
            <td>Total whole years</td>
        </tr>
    </tbody>
</table>

### Examples

```ts
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);  // 9000000000000n
```

## Instance methods

### `.toString()` {#tostring}

Convert to human-readable string.

```ts title="Syntax"
duration.toString()
```

#### Returns
`string` - Human-readable duration string

#### Example

```ts
const duration = new Duration('2h30m15s');
console.log(duration.toString()); // '2h30m15s'
```

---

### `.toJSON()` {#tojson}

Serialise for JSON.

```ts title="Syntax"
duration.toJSON()
```

#### Returns
`string` - Duration string for JSON

---

### `.toCompact()` {#tocompact}

Convert to a compact tuple representation.

```ts title="Syntax"
duration.toCompact()
```

#### Returns
`[bigint, bigint] | [bigint] | []` - Compact representation: `[seconds, nanoseconds]`, `[seconds]` if nanoseconds is zero, or `[]` for a zero duration.

#### Example

```ts
const d = new Duration('5m30s');
console.log(d.toCompact()); // [330n, 0n] or [330n]
```

---

### `.add(other)` {#add}

Add another duration.

```ts title="Syntax"
duration.add(other)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>other</code> <label label="required" /></td>
            <td><code>Duration</code></td>
            <td>Duration to add.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Sum of durations

#### Example

```ts
const base = new Duration('1h');
const extra = new Duration('30m');
const total = base.add(extra);
console.log(total.toString()); // '1h30m'
```

---

### `.sub(other)` {#sub}

Subtract another duration.

```ts title="Syntax"
duration.sub(other)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>other</code> <label label="required" /></td>
            <td><code>Duration</code></td>
            <td>Duration to subtract.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Difference of durations

#### Example

```ts
const total = new Duration('2h');
const part = new Duration('30m');
const remaining = total.sub(part);
console.log(remaining.toString()); // '1h30m'
```

---

### `.mul(factor)` {#mul}

Multiply a duration by a scalar.

```ts title="Syntax"
duration.mul(factor)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>factor</code> <label label="required" /></td>
            <td><code>number | bigint</code></td>
            <td>Scalar to multiply by.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Scaled duration

#### Example

```ts
const base = new Duration('30m');
const doubled = base.mul(2);
console.log(doubled.toString()); // '1h'
```

---

### `.div(divisor)` {#div}

Divide a duration. Overloaded: dividing by a `Duration` returns the ratio as `bigint`, dividing by a number returns a new `Duration`.

```ts title="Syntax"
duration.div(divisor: Duration)       // Returns bigint (ratio)
duration.div(divisor: number | bigint) // Returns Duration
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>divisor</code> <label label="required" /></td>
            <td><code>Duration | number | bigint</code></td>
            <td>Duration for ratio, or scalar for division.</td>
        </tr>
    </tbody>
</table>

#### Returns
`bigint` when dividing by a `Duration`, `Duration` when dividing by a number or bigint.

#### Examples

```ts
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)` {#mod}

Get the remainder after dividing by another duration.

```ts title="Syntax"
duration.mod(mod)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>mod</code> <label label="required" /></td>
            <td><code>Duration</code></td>
            <td>Duration to divide by.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Duration` - Remainder after division

#### Example

```ts
const total = new Duration('2h20m');
const interval = new Duration('1h');
const remainder = total.mod(interval);
console.log(remainder.toString()); // '20m'
```

---

### `.equals(other)` {#equals}

Check if two durations are equal.

```ts title="Syntax"
duration.equals(other)
```

#### Returns
`boolean` - True if equal

## Complete examples

### Timeouts and expiration

```ts
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

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

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

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

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

```ts
// Measure operation duration
const elapsed = Duration.measure();

// ... perform operation ...

const duration = elapsed();
console.log('Operation took:', duration.toString());
```

### Conversion examples

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

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

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

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

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

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

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

```ts
// Good: Built-in measurement
const elapsed = Duration.measure();
await performOperation();
console.log('Took:', elapsed().toString());
```

## See also

- [DateTime](/docs/reference/javascript/api/values/datetime.md) - Datetime values
- [Data types overview](/docs/reference/javascript/api/values/) - All custom data types
- [Query builders](/docs/reference/javascript/api/queries/) - Using Duration in queries
- [SurrealQL durations](/docs/reference/query-language/language-primitives/data-types/durations.md) - Database duration type
