0
# Temporal Data Types
1
2
Neo4j temporal data types including dates, times, and durations with timezone support and comprehensive type checking.
3
4
## Capabilities
5
6
### Date Type
7
8
Represents a date without time components.
9
10
```typescript { .api }
11
interface Date {
12
/** Year component */
13
year: Integer;
14
15
/** Month component (1-12) */
16
month: Integer;
17
18
/** Day component (1-31) */
19
day: Integer;
20
21
/** Convert to ISO date string (YYYY-MM-DD) */
22
toString(): string;
23
}
24
25
/**
26
* Check if an object is a Neo4j Date
27
* @param obj - Object to check
28
* @returns true if object is a Date instance
29
*/
30
function isDate(obj: any): obj is Date;
31
```
32
33
**Usage Examples:**
34
35
```typescript
36
import { driver, auth, isDate } from "neo4j-driver";
37
38
const session = neo4jDriver.session();
39
40
try {
41
const result = await session.run(`
42
CREATE (e:Event {
43
name: $name,
44
startDate: date($dateStr),
45
endDate: date() // Current date
46
})
47
RETURN e.startDate AS start, e.endDate AS end
48
`, {
49
name: "Conference 2024",
50
dateStr: "2024-06-15"
51
});
52
53
const record = result.records[0];
54
const startDate = record.get("start");
55
const endDate = record.get("end");
56
57
if (isDate(startDate)) {
58
console.log(`Event starts on: ${startDate.toString()}`); // "2024-06-15"
59
console.log(`Year: ${startDate.year}, Month: ${startDate.month}, Day: ${startDate.day}`);
60
}
61
62
if (isDate(endDate)) {
63
console.log(`Event ends on: ${endDate.toString()}`);
64
}
65
} finally {
66
await session.close();
67
}
68
```
69
70
### DateTime Type
71
72
Represents a date and time with optional timezone information.
73
74
```typescript { .api }
75
interface DateTime {
76
/** Year component */
77
year: Integer;
78
79
/** Month component (1-12) */
80
month: Integer;
81
82
/** Day component (1-31) */
83
day: Integer;
84
85
/** Hour component (0-23) */
86
hour: Integer;
87
88
/** Minute component (0-59) */
89
minute: Integer;
90
91
/** Second component (0-59) */
92
second: Integer;
93
94
/** Nanosecond component (0-999999999) */
95
nanosecond: Integer;
96
97
/** Timezone offset in seconds (optional) */
98
timeZoneOffsetSeconds?: Integer;
99
100
/** Timezone identifier (optional) */
101
timeZoneId?: string;
102
103
/** Convert to ISO datetime string */
104
toString(): string;
105
}
106
107
/**
108
* Check if an object is a Neo4j DateTime
109
* @param obj - Object to check
110
* @returns true if object is a DateTime instance
111
*/
112
function isDateTime(obj: any): obj is DateTime;
113
```
114
115
**Usage Examples:**
116
117
```typescript
118
const result = await session.run(`
119
CREATE (log:LogEntry {
120
message: $message,
121
timestamp: datetime(),
122
scheduledFor: datetime($futureTime)
123
})
124
RETURN log.timestamp AS now, log.scheduledFor AS future
125
`, {
126
message: "System started",
127
futureTime: "2024-12-25T09:00:00Z"
128
});
129
130
const record = result.records[0];
131
const now = record.get("now");
132
const future = record.get("future");
133
134
if (isDateTime(now)) {
135
console.log(`Current time: ${now.toString()}`);
136
console.log(`${now.year}-${now.month}-${now.day} ${now.hour}:${now.minute}:${now.second}`);
137
138
if (now.timeZoneId) {
139
console.log(`Timezone: ${now.timeZoneId}`);
140
} else if (now.timeZoneOffsetSeconds !== undefined) {
141
console.log(`Timezone offset: ${now.timeZoneOffsetSeconds} seconds`);
142
}
143
}
144
145
if (isDateTime(future)) {
146
console.log(`Scheduled for: ${future.toString()}`);
147
console.log(`Christmas morning: ${future.month}/25 at ${future.hour}:00`);
148
}
149
```
150
151
### LocalDateTime Type
152
153
Represents a date and time without timezone information.
154
155
```typescript { .api }
156
interface LocalDateTime {
157
/** Year component */
158
year: Integer;
159
160
/** Month component (1-12) */
161
month: Integer;
162
163
/** Day component (1-31) */
164
day: Integer;
165
166
/** Hour component (0-23) */
167
hour: Integer;
168
169
/** Minute component (0-59) */
170
minute: Integer;
171
172
/** Second component (0-59) */
173
second: Integer;
174
175
/** Nanosecond component (0-999999999) */
176
nanosecond: Integer;
177
178
/** Convert to ISO local datetime string */
179
toString(): string;
180
}
181
182
/**
183
* Check if an object is a Neo4j LocalDateTime
184
* @param obj - Object to check
185
* @returns true if object is a LocalDateTime instance
186
*/
187
function isLocalDateTime(obj: any): obj is LocalDateTime;
188
```
189
190
**Usage Examples:**
191
192
```typescript
193
const result = await session.run(`
194
CREATE (appt:Appointment {
195
title: $title,
196
localTime: localdatetime($timeStr),
197
created: localdatetime()
198
})
199
RETURN appt.localTime AS scheduled, appt.created AS created
200
`, {
201
title: "Team Meeting",
202
timeStr: "2024-06-15T14:30:00"
203
});
204
205
const record = result.records[0];
206
const scheduled = record.get("scheduled");
207
const created = record.get("created");
208
209
if (isLocalDateTime(scheduled)) {
210
console.log(`Meeting scheduled: ${scheduled.toString()}`); // "2024-06-15T14:30:00"
211
console.log(`Date: ${scheduled.year}-${scheduled.month}-${scheduled.day}`);
212
console.log(`Time: ${scheduled.hour}:${scheduled.minute}`);
213
}
214
215
if (isLocalDateTime(created)) {
216
console.log(`Appointment created: ${created.toString()}`);
217
}
218
```
219
220
### Time Type
221
222
Represents a time with timezone information.
223
224
```typescript { .api }
225
interface Time {
226
/** Hour component (0-23) */
227
hour: Integer;
228
229
/** Minute component (0-59) */
230
minute: Integer;
231
232
/** Second component (0-59) */
233
second: Integer;
234
235
/** Nanosecond component (0-999999999) */
236
nanosecond: Integer;
237
238
/** Timezone offset in seconds (optional) */
239
timeZoneOffsetSeconds?: Integer;
240
241
/** Timezone identifier (optional) */
242
timeZoneId?: string;
243
244
/** Convert to ISO time string */
245
toString(): string;
246
}
247
248
/**
249
* Check if an object is a Neo4j Time
250
* @param obj - Object to check
251
* @returns true if object is a Time instance
252
*/
253
function isTime(obj: any): obj is Time;
254
```
255
256
**Usage Examples:**
257
258
```typescript
259
const result = await session.run(`
260
CREATE (schedule:DailySchedule {
261
name: $name,
262
startTime: time($startStr),
263
endTime: time($endStr),
264
currentTime: time()
265
})
266
RETURN schedule.startTime AS start, schedule.endTime AS end, schedule.currentTime AS current
267
`, {
268
name: "Work Hours",
269
startStr: "09:00:00+02:00",
270
endStr: "17:30:00+02:00"
271
});
272
273
const record = result.records[0];
274
const startTime = record.get("start");
275
const endTime = record.get("end");
276
const currentTime = record.get("current");
277
278
if (isTime(startTime)) {
279
console.log(`Work starts at: ${startTime.toString()}`); // "09:00:00+02:00"
280
console.log(`Hour: ${startTime.hour}, Minute: ${startTime.minute}`);
281
282
if (startTime.timeZoneId) {
283
console.log(`Timezone: ${startTime.timeZoneId}`);
284
} else if (startTime.timeZoneOffsetSeconds !== undefined) {
285
console.log(`Offset: ${startTime.timeZoneOffsetSeconds / 3600} hours`);
286
}
287
}
288
289
if (isTime(endTime)) {
290
console.log(`Work ends at: ${endTime.toString()}`);
291
}
292
```
293
294
### LocalTime Type
295
296
Represents a time without timezone information.
297
298
```typescript { .api }
299
interface LocalTime {
300
/** Hour component (0-23) */
301
hour: Integer;
302
303
/** Minute component (0-59) */
304
minute: Integer;
305
306
/** Second component (0-59) */
307
second: Integer;
308
309
/** Nanosecond component (0-999999999) */
310
nanosecond: Integer;
311
312
/** Convert to ISO local time string */
313
toString(): string;
314
}
315
316
/**
317
* Check if an object is a Neo4j LocalTime
318
* @param obj - Object to check
319
* @returns true if object is a LocalTime instance
320
*/
321
function isLocalTime(obj: any): obj is LocalTime;
322
```
323
324
**Usage Examples:**
325
326
```typescript
327
const result = await session.run(`
328
CREATE (routine:DailyRoutine {
329
activity: $activity,
330
localStartTime: localtime($timeStr),
331
currentLocalTime: localtime()
332
})
333
RETURN routine.localStartTime AS start, routine.currentLocalTime AS current
334
`, {
335
activity: "Morning Workout",
336
timeStr: "06:30:00"
337
});
338
339
const record = result.records[0];
340
const startTime = record.get("start");
341
342
if (isLocalTime(startTime)) {
343
console.log(`Workout starts at: ${startTime.toString()}`); // "06:30:00"
344
console.log(`${startTime.hour}:${startTime.minute} (local time)`);
345
}
346
```
347
348
### Duration Type
349
350
Represents a temporal duration between two points in time.
351
352
```typescript { .api }
353
interface Duration {
354
/** Number of months in the duration */
355
months: Integer;
356
357
/** Number of days in the duration */
358
days: Integer;
359
360
/** Number of seconds in the duration */
361
seconds: Integer;
362
363
/** Number of nanoseconds in the duration */
364
nanoseconds: Integer;
365
366
/** Convert to ISO duration string */
367
toString(): string;
368
}
369
370
/**
371
* Check if an object is a Neo4j Duration
372
* @param obj - Object to check
373
* @returns true if object is a Duration instance
374
*/
375
function isDuration(obj: any): obj is Duration;
376
```
377
378
**Usage Examples:**
379
380
```typescript
381
const result = await session.run(`
382
MATCH (start:Event {name: $startEvent}), (end:Event {name: $endEvent})
383
WITH start, end, duration.between(start.timestamp, end.timestamp) AS eventDuration
384
CREATE (span:TimeSpan {
385
startEvent: start.name,
386
endEvent: end.name,
387
duration: eventDuration,
388
calculatedAt: datetime()
389
})
390
RETURN span.duration AS duration
391
`, {
392
startEvent: "Project Start",
393
endEvent: "Project End"
394
});
395
396
const record = result.records[0];
397
const duration = record.get("duration");
398
399
if (isDuration(duration)) {
400
console.log(`Project duration: ${duration.toString()}`); // "P2M15DT8H30M"
401
402
// Break down duration components
403
console.log(`Months: ${duration.months}`);
404
console.log(`Days: ${duration.days}`);
405
console.log(`Hours: ${Math.floor(duration.seconds.toNumber() / 3600)}`);
406
console.log(`Minutes: ${Math.floor((duration.seconds.toNumber() % 3600) / 60)}`);
407
console.log(`Seconds: ${duration.seconds.toNumber() % 60}`);
408
409
// Convert to approximate total days
410
const totalDays = duration.months.toNumber() * 30 + duration.days.toNumber() +
411
duration.seconds.toNumber() / (24 * 3600);
412
console.log(`Approximately ${totalDays.toFixed(1)} total days`);
413
}
414
415
// Create durations in Cypher
416
const createResult = await session.run(`
417
CREATE (task:Task {
418
name: $name,
419
estimatedDuration: duration($durationStr),
420
warningThreshold: duration({hours: 2}),
421
maxDuration: duration({days: 7, hours: 12, minutes: 30})
422
})
423
RETURN task.estimatedDuration AS estimated,
424
task.warningThreshold AS warning,
425
task.maxDuration AS max
426
`, {
427
name: "Data Migration",
428
durationStr: "PT4H30M" // 4 hours 30 minutes
429
});
430
431
createResult.records.forEach(record => {
432
const estimated = record.get("estimated");
433
const warning = record.get("warning");
434
const max = record.get("max");
435
436
if (isDuration(estimated)) {
437
console.log(`Estimated time: ${estimated.toString()}`);
438
}
439
if (isDuration(warning)) {
440
console.log(`Warning threshold: ${warning.toString()}`);
441
}
442
if (isDuration(max)) {
443
console.log(`Maximum duration: ${max.toString()}`);
444
}
445
});
446
```
447
448
### Temporal Type Utilities
449
450
Utility object containing all temporal type checking functions.
451
452
```typescript { .api }
453
declare const temporal: {
454
/** Check if object is a Date */
455
isDate: typeof isDate;
456
457
/** Check if object is a DateTime */
458
isDateTime: typeof isDateTime;
459
460
/** Check if object is a LocalDateTime */
461
isLocalDateTime: typeof isLocalDateTime;
462
463
/** Check if object is a Time */
464
isTime: typeof isTime;
465
466
/** Check if object is a LocalTime */
467
isLocalTime: typeof isLocalTime;
468
469
/** Check if object is a Duration */
470
isDuration: typeof isDuration;
471
};
472
```
473
474
**Usage Examples:**
475
476
```typescript
477
import { temporal } from "neo4j-driver";
478
479
const result = await session.run(`
480
RETURN date() AS currentDate,
481
datetime() AS currentDateTime,
482
time() AS currentTime,
483
localdatetime() AS localNow,
484
localtime() AS localTime,
485
duration({hours: 2, minutes: 30}) AS sampleDuration
486
`);
487
488
const record = result.records[0];
489
490
// Generic temporal type analysis
491
function analyzeTemporalValue(value: any, name: string) {
492
if (temporal.isDate(value)) {
493
console.log(`${name} is a Date: ${value.toString()}`);
494
} else if (temporal.isDateTime(value)) {
495
console.log(`${name} is a DateTime: ${value.toString()}`);
496
if (value.timeZoneId) {
497
console.log(` Timezone: ${value.timeZoneId}`);
498
}
499
} else if (temporal.isLocalDateTime(value)) {
500
console.log(`${name} is a LocalDateTime: ${value.toString()}`);
501
} else if (temporal.isTime(value)) {
502
console.log(`${name} is a Time: ${value.toString()}`);
503
} else if (temporal.isLocalTime(value)) {
504
console.log(`${name} is a LocalTime: ${value.toString()}`);
505
} else if (temporal.isDuration(value)) {
506
console.log(`${name} is a Duration: ${value.toString()}`);
507
} else {
508
console.log(`${name} is not a temporal type`);
509
}
510
}
511
512
// Analyze all temporal values
513
record.keys.forEach(key => {
514
analyzeTemporalValue(record.get(key), key);
515
});
516
517
// Working with temporal comparisons
518
const comparisonResult = await session.run(`
519
WITH datetime('2024-06-15T10:30:00Z') AS start,
520
datetime('2024-06-15T14:45:00Z') AS end
521
RETURN start < end AS isBefore,
522
duration.between(start, end) AS timeDiff,
523
start + duration({hours: 3}) AS startPlusThree
524
`);
525
526
const compRecord = comparisonResult.records[0];
527
console.log(`Start is before end: ${compRecord.get("isBefore")}`);
528
529
const timeDiff = compRecord.get("timeDiff");
530
if (temporal.isDuration(timeDiff)) {
531
console.log(`Time difference: ${timeDiff.toString()}`);
532
}
533
534
const startPlusThree = compRecord.get("startPlusThree");
535
if (temporal.isDateTime(startPlusThree)) {
536
console.log(`Start + 3 hours: ${startPlusThree.toString()}`);
537
}
538
```