# DateTime

Datetime values with nanosecond precision for time-based operations.

The `DateTime` class provides datetime values with nanosecond precision, extending the abstract `Value` class to match SurrealDB's datetime type.

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

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

## Constructor

### `new DateTime(value?)` {#constructor}

Create a new datetime value.

```ts title="Syntax"
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
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>value</code> <label label="optional" /></td>
            <td><code>DateTime | Date | string | number | bigint | [bigint, bigint]</code></td>
            <td>Value to create datetime from. If omitted, uses current time.</td>
        </tr>
    </tbody>
</table>

#### Examples

```ts
// 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()` {#now}

Get the current datetime with nanosecond precision.

```ts title="Syntax"
DateTime.now()
```

#### Returns
`DateTime` - Current datetime

#### Example

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

Returns a `DateTime` representing the Unix epoch (1970-01-01T00:00:00Z).

```ts title="Syntax"
DateTime.epoch()
```

#### Returns
`DateTime` - Unix epoch datetime

#### Example

```ts
const epoch = DateTime.epoch();
console.log(epoch.toString()); // '1970-01-01T00:00:00.000000000Z'
console.log(epoch.seconds); // 0
```

---

### `DateTime.fromEpochNanoseconds(ns)` {#fromepochnanoseconds}

Create a `DateTime` from a nanosecond timestamp since Unix epoch.

```ts title="Syntax"
DateTime.fromEpochNanoseconds(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>Nanoseconds since Unix epoch.</td>
        </tr>
    </tbody>
</table>

#### Returns
`DateTime` - Datetime from the nanosecond timestamp

#### Example

```ts
const dt = DateTime.fromEpochNanoseconds(1705320000123456789n);
console.log(dt.toString()); // '2024-01-15T12:00:00.123456789Z'
```

---

### `DateTime.fromEpochMicroseconds(µs)` {#fromepochmicroseconds}

Create a `DateTime` from a microsecond timestamp since Unix epoch.

```ts title="Syntax"
DateTime.fromEpochMicroseconds(µ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>Microseconds since Unix epoch.</td>
        </tr>
    </tbody>
</table>

#### Returns
`DateTime` - Datetime from the microsecond timestamp

#### Example

```ts
const dt = DateTime.fromEpochMicroseconds(1705320000123456n);
console.log(dt.toString()); // '2024-01-15T12:00:00.123456000Z'
```

---

### `DateTime.fromEpochMilliseconds(ms)` {#fromepochmilliseconds}

Create a `DateTime` from a millisecond timestamp since Unix epoch.

```ts title="Syntax"
DateTime.fromEpochMilliseconds(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>Milliseconds since Unix epoch.</td>
        </tr>
    </tbody>
</table>

#### Returns
`DateTime` - Datetime from the millisecond timestamp

#### Example

```ts
const dt = DateTime.fromEpochMilliseconds(1705320000123);
console.log(dt.toString()); // '2024-01-15T12:00:00.123000000Z'
```

---

### `DateTime.fromEpochSeconds(s)` {#fromepochseconds}

Create a `DateTime` from a second timestamp since Unix epoch.

```ts title="Syntax"
DateTime.fromEpochSeconds(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>Seconds since Unix epoch.</td>
        </tr>
    </tbody>
</table>

#### Returns
`DateTime` - Datetime from the second timestamp

#### Example

```ts
const dt = DateTime.fromEpochSeconds(1705320000);
console.log(dt.toString()); // '2024-01-15T12:00:00.000000000Z'
```

## Instance methods

### `.toDate()` {#todate}

Convert to JavaScript Date object.

```ts title="Syntax"
datetime.toDate()
```

#### Returns
`Date` - JavaScript Date (millisecond precision)

> [!WARNING]
> JavaScript Date only supports millisecond precision. Nanosecond precision is lost in conversion.

> [!NOTE]
> `DateTime` does not extend JavaScript's `Date`. To use `Date` methods like `.getFullYear()`, `.getMonth()`, `.getDate()`, `.getHours()`, etc., first call `.toDate()`.

#### Example

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

Convert to ISO 8601 string with full nanosecond precision.

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

#### Returns
`string` - ISO 8601 formatted string

#### Example

```ts
const dt = DateTime.now();
console.log(dt.toString());
// '2024-01-15T12:30:45.123456789Z'
```

---

### `.toISOString()` {#toisostring}

Convert to ISO 8601 string (alias for `.toString()`).

```ts title="Syntax"
datetime.toISOString()
```

#### Returns
`string` - ISO 8601 formatted string

---

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

Serialise for JSON.

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

#### Returns
`string` - ISO string for JSON serialisation

#### Example

```ts
const dt = DateTime.now();
console.log(JSON.stringify({ timestamp: dt }));
// {"timestamp":"2024-01-15T12:30:45.123456789Z"}
```

---

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

Returns the datetime as a compact tuple of seconds and nanoseconds since Unix epoch.

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

#### Returns
`[bigint, bigint]` - Tuple of `[seconds, nanoseconds]`

#### Example

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

Add a duration to the datetime.

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

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>duration</code> <label label="required" /></td>
            <td><code><a href="/docs/reference/javascript/api/values/duration.md">Duration</a></code></td>
            <td>Duration to add.</td>
        </tr>
    </tbody>
</table>

#### Returns
`DateTime` - New datetime with duration added

#### Example

```ts
import { Duration } from 'surrealdb';

const now = DateTime.now();
const later = now.add(Duration.parse('1h30m'));
const tomorrow = now.add(Duration.parse('24h'));
```

---

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

Subtract a duration from the datetime.

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

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>duration</code> <label label="required" /></td>
            <td><code><a href="/docs/reference/javascript/api/values/duration.md">Duration</a></code></td>
            <td>Duration to subtract.</td>
        </tr>
    </tbody>
</table>

#### Returns
`DateTime` - New datetime with duration subtracted

#### Example

```ts
const now = DateTime.now();
const earlier = now.sub(Duration.parse('1h'));
const yesterday = now.sub(Duration.parse('24h'));
```

---

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

Calculate the duration between two datetimes.

```ts title="Syntax"
datetime.diff(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>DateTime</code></td>
            <td>The other datetime to calculate the difference from.</td>
        </tr>
    </tbody>
</table>

#### Returns
[`Duration`](/docs/reference/javascript/api/values/duration.md) - Duration between the two datetimes

#### Example

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

Compare two datetimes for ordering.

```ts title="Syntax"
datetime.compare(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>DateTime</code></td>
            <td>The datetime to compare against.</td>
        </tr>
    </tbody>
</table>

#### Returns
`number` - Returns `-1` if this datetime is before `other`, `0` if equal, `1` if after

#### Example

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

Check if two datetimes are equal (including nanosecond precision).

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

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

## Properties

### `nanoseconds` {#nanoseconds}

Total nanoseconds since Unix epoch.

**Type:** `bigint`

```ts
const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.nanoseconds); // 1705320000123456789n
```

---

### `microseconds` {#microseconds}

Total microseconds since Unix epoch.

**Type:** `bigint`

```ts
const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.microseconds); // 1705320000123456n
```

---

### `milliseconds` {#milliseconds}

Total milliseconds since Unix epoch.

**Type:** `number`

```ts
const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.milliseconds); // 1705320000123
```

---

### `seconds` {#seconds}

Seconds since Unix epoch.

**Type:** `number`

```ts
const dt = new DateTime('2024-01-15T12:00:00.123456789Z');
console.log(dt.seconds); // 1705320000
```

## Complete examples

### Event timestamps

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

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

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

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

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

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

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

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

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

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

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

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

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