1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624import { DateTime } from 'luxon';
import type {
DateTimeUnit,
DurationLike,
DurationObjectUnits,
LocaleOptions,
WeekdayNumbers,
} from 'luxon';
import type { ExtensionMap } from './extensions';
import { toDateTime as stringToDateTime } from './string-extensions';
import { convertToDateTime } from './utils';
import { ExpressionExtensionError } from '../errors/expression-extension.error';
const durationUnits = [
'milliseconds',
'seconds',
'minutes',
'hours',
'days',
'weeks',
'months',
'quarters',
'years',
] as const;
type DurationUnit = (typeof durationUnits)[number];
const dateParts = [
'day',
'week',
'month',
'year',
'hour',
'minute',
'second',
'millisecond',
'weekNumber',
'yearDayNumber',
'weekday',
] as const;
type DatePart = (typeof dateParts)[number];
const DURATION_MAP: Record<string, DurationUnit> = {
day: 'days',
month: 'months',
year: 'years',
week: 'weeks',
hour: 'hours',
minute: 'minutes',
second: 'seconds',
millisecond: 'milliseconds',
ms: 'milliseconds',
sec: 'seconds',
secs: 'seconds',
hr: 'hours',
hrs: 'hours',
min: 'minutes',
mins: 'minutes',
};
const DATETIMEUNIT_MAP: Record<string, DateTimeUnit> = {
days: 'day',
months: 'month',
years: 'year',
hours: 'hour',
minutes: 'minute',
seconds: 'second',
milliseconds: 'millisecond',
hrs: 'hour',
hr: 'hour',
mins: 'minute',
min: 'minute',
secs: 'second',
sec: 'second',
ms: 'millisecond',
};
function isDateTime(date: unknown): date is DateTime {
return date ? DateTime.isDateTime(date) : false;
}
function toDateTime(date: string | Date | DateTime): DateTime {
if (isDateTime(date)) return date;
if (typeof date === 'string') {
return stringToDateTime(date);
}
return DateTime.fromJSDate(date);
}
function generateDurationObject(durationValue: number, unit: DurationUnit): DurationObjectUnits {
const convertedUnit = DURATION_MAP[unit] || unit;
return { [`${convertedUnit}`]: durationValue };
}
function beginningOf(date: Date | DateTime, extraArgs: DurationUnit[]): Date | DateTime {
const [rawUnit = 'week'] = extraArgs;
const unit = DATETIMEUNIT_MAP[rawUnit] || rawUnit;
if (isDateTime(date)) return date.startOf(unit);
return DateTime.fromJSDate(date).startOf(unit).toJSDate();
}
function endOfMonth(date: Date | DateTime): Date | DateTime {
if (isDateTime(date)) return date.endOf('month');
return DateTime.fromJSDate(date).endOf('month').toJSDate();
}
function extract(date: Date | DateTime, args: DatePart[]): number {
let [part = 'week'] = args;
if (part === 'yearDayNumber') {
date = isDateTime(date) ? date.toJSDate() : date;
const firstDayOfTheYear = new Date(date.getFullYear(), 0, 0);
const diff =
date.getTime() -
firstDayOfTheYear.getTime() +
(firstDayOfTheYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;
return Math.floor(diff / (1000 * 60 * 60 * 24));
}
if (part === 'week') part = 'weekNumber';
const unit = (DATETIMEUNIT_MAP[part] as keyof DateTime) || part;
if (isDateTime(date)) return date.get(unit);
return DateTime.fromJSDate(date).get(unit);
}
function format(date: Date | DateTime, extraArgs: unknown[]): string {
const [dateFormat, localeOpts = {}] = extraArgs as [string, LocaleOptions];
if (isDateTime(date)) {
return date.toFormat(dateFormat, { ...localeOpts });
}
return DateTime.fromJSDate(date).toFormat(dateFormat, { ...localeOpts });
}
function isBetween(
date: Date | DateTime,
extraArgs: Array<string | Date | DateTime>,
): boolean | undefined {
if (extraArgs.length !== 2) {
throw new ExpressionExtensionError('isBetween(): expected exactly two args');
}
const [first, second] = extraArgs;
const firstDate = convertToDateTime(first);
const secondDate = convertToDateTime(second);
if (!firstDate || !secondDate) {
return;
}
if (firstDate > secondDate) {
return secondDate < date && date < firstDate;
}
return secondDate > date && date > firstDate;
}
function isDst(date: Date | DateTime): boolean {
if (isDateTime(date)) {
return date.isInDST;
}
return DateTime.fromJSDate(date).isInDST;
}
function isInLast(date: Date | DateTime, extraArgs: unknown[]): boolean {
const [durationValue = 0, unit = 'minutes'] = extraArgs as [number, DurationUnit];
const dateInThePast = DateTime.now().minus(generateDurationObject(durationValue, unit));
let thisDate = date;
if (!isDateTime(thisDate)) {
thisDate = DateTime.fromJSDate(thisDate);
}
return dateInThePast <= thisDate && thisDate <= DateTime.now();
}
const WEEKEND_DAYS: WeekdayNumbers[] = [6, 7];
function isWeekend(date: Date | DateTime): boolean {
const { weekday } = isDateTime(date) ? date : DateTime.fromJSDate(date);
return WEEKEND_DAYS.includes(weekday);
}
function minus(
date: Date | DateTime,
args: [DurationLike] | [number, DurationUnit],
): Date | DateTime {
if (args.length === 1) {
const [arg] = args;
if (isDateTime(date)) return date.minus(arg);
return DateTime.fromJSDate(date).minus(arg).toJSDate();
}
const [durationValue = 0, unit = 'minutes'] = args;
const duration = generateDurationObject(durationValue, unit);
if (isDateTime(date)) return date.minus(duration);
return DateTime.fromJSDate(date).minus(duration).toJSDate();
}
function plus(
date: Date | DateTime,
args: [DurationLike] | [number, DurationUnit],
): Date | DateTime {
if (args.length === 1) {
const [arg] = args;
if (isDateTime(date)) return date.plus(arg);
return DateTime.fromJSDate(date).plus(arg).toJSDate();
}
const [durationValue = 0, unit = 'minutes'] = args;
const duration = generateDurationObject(durationValue, unit);
if (isDateTime(date)) return date.plus(duration);
return DateTime.fromJSDate(date).plus(duration).toJSDate();
}
function diffTo(date: DateTime, args: [string | Date | DateTime, DurationUnit | DurationUnit[]]) {
const [otherDate, unit = 'days'] = args;
let units = Array.isArray(unit) ? unit : [unit];
if (units.length === 0) {
units = ['days'];
}
const allowedUnitSet = new Set([...dateParts, ...durationUnits]);
const errorUnit = units.find((u) => !allowedUnitSet.has(u));
if (errorUnit) {
throw new ExpressionExtensionError(
`Unsupported unit '${String(errorUnit)}'. Supported: ${durationUnits
.map((u) => `'${u}'`)
.join(', ')}.`,
);
}
const diffResult = date.diff(toDateTime(otherDate), units);
if (units.length > 1) {
return diffResult.toObject();
}
return diffResult.as(units[0]);
}
function diffToNow(date: DateTime, args: [DurationUnit | DurationUnit[]]) {
const [unit] = args;
return diffTo(date, [DateTime.now(), unit]);
}
function toInt(date: Date | DateTime): number {
if (isDateTime(date)) {
return date.toMillis();
}
return date.getTime();
}
const toFloat = toInt;
function toBoolean() {
return undefined;
}
// Only null/undefined return true, this is handled in ExpressionExtension.ts
function isEmpty(): boolean {
return false;
}
function isNotEmpty(): boolean {
return true;
}
endOfMonth.doc = {
name: 'endOfMonth',
returnType: 'DateTime',
hidden: true,
description: 'Transforms a date to the last possible moment that lies within the month.',
section: 'edit',
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-endOfMonth',
};
isDst.doc = {
name: 'isDst',
returnType: 'boolean',
hidden: true,
description: 'Checks if a Date is within Daylight Savings Time.',
section: 'query',
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-isDst',
};
isWeekend.doc = {
name: 'isWeekend',
returnType: 'boolean',
hidden: true,
description: 'Checks if the Date falls on a Saturday or Sunday.',
section: 'query',
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-isWeekend',
};
beginningOf.doc = {
name: 'beginningOf',
description: 'Transform a Date to the start of the given time period. Default unit is `week`.',
section: 'edit',
hidden: true,
returnType: 'DateTime',
args: [{ name: 'unit?', type: 'DurationUnit' }],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-beginningOf',
};
extract.doc = {
name: 'extract',
description:
'Extracts a part of the date or time, e.g. the month, as a number. To extract textual names instead, see <code>format()</code>.',
examples: [
{ example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.extract('month')", evaluated: '3' },
{ example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.extract('hour')", evaluated: '18' },
],
section: 'query',
returnType: 'number',
args: [
{
name: 'unit',
optional: true,
description:
'The part of the date or time to return. One of: <code>year</code>, <code>month</code>, <code>week</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, <code>second</code>',
default: '"week"',
type: 'string',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-extract',
};
format.doc = {
name: 'format',
description:
'Converts the DateTime to a string, using the format specified. <a target="_blank" href="https://moment.github.io/luxon/#/formatting?id=table-of-tokens">Formatting guide</a>. For common formats, <code>toLocaleString()</code> may be easier.',
examples: [
{
example: "dt = '2024-04-30T18:49'.toDateTime()\ndt.format('dd/LL/yyyy')",
evaluated: "'30/04/2024'",
},
{
example: "dt = '2024-04-30T18:49'.toDateTime()\ndt.format('dd LLL yy')",
evaluated: "'30 Apr 24'",
},
{
example: "dt = '2024-04-30T18:49'.toDateTime()\ndt.setLocale('fr').format('dd LLL yyyy')",
evaluated: "'30 avr. 2024'",
},
{
example: "dt = '2024-04-30T18:49'.toDateTime()\ndt.format(\"HH 'hours and' mm 'minutes'\")",
evaluated: "'18 hours and 49 minutes'",
},
],
returnType: 'string',
section: 'format',
args: [
{
name: 'fmt',
description:
'The <a target="_blank" href="https://moment.github.io/luxon/#/formatting?id=table-of-tokens">format</a> of the string to return ',
default: "'yyyy-MM-dd'",
type: 'string',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-format',
};
isBetween.doc = {
name: 'isBetween',
description: 'Returns <code>true</code> if the DateTime lies between the two moments specified',
examples: [
{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.isBetween('2020-06-01', '2025-06-01')",
evaluated: 'true',
},
{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.isBetween('2020', '2025')",
evaluated: 'true',
},
],
section: 'compare',
returnType: 'boolean',
args: [
{
name: 'date1',
description:
'The moment that the base DateTime must be after. Can be an ISO date string or a Luxon DateTime.',
type: 'string | DateTime',
},
{
name: 'date2',
description:
'The moment that the base DateTime must be before. Can be an ISO date string or a Luxon DateTime.',
type: 'string | DateTime',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-isBetween',
};
isInLast.doc = {
name: 'isInLast',
hidden: true,
description: 'Checks if a Date is within a given time period. Default unit is `minute`.',
section: 'query',
returnType: 'boolean',
args: [
{ name: 'n', type: 'number' },
{ name: 'unit?', type: 'DurationUnit' },
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-isInLast',
};
toDateTime.doc = {
name: 'toDateTime',
description:
'Converts a JavaScript Date to a Luxon DateTime. The DateTime contains the same information, but is easier to manipulate.',
examples: [
{
example: "jsDate = new Date('2024-03-30T18:49')\njsDate.toDateTime().plus(5, 'days')",
evaluated: '[DateTime: 2024-05-05T18:49:00.000Z]',
},
],
returnType: 'DateTime',
hidden: true,
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-toDateTime',
};
minus.doc = {
name: 'minus',
description: 'Subtracts a given period of time from the DateTime',
examples: [
{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.minus(7, 'days')",
evaluated: '[DateTime: 2024-04-23T18:49:00.000Z]',
},
{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.minus(4, 'years')",
evaluated: '[DateTime: 2020-04-30T18:49:00.000Z]',
},
],
section: 'edit',
returnType: 'DateTime',
args: [
{
name: 'n',
description:
'The number of units to subtract. Or use a Luxon <a target="_blank" href=”https://moment.github.io/luxon/api-docs/index.html#duration”>Duration</a> object to subtract multiple units at once.',
type: 'number | object',
},
{
name: 'unit',
optional: true,
description:
'The units of the number. One of: <code>years</code>, <code>months</code>, <code>weeks</code>, <code>days</code>, <code>hours</code>, <code>minutes</code>, <code>seconds</code>, <code>milliseconds</code>',
default: '"milliseconds"',
type: 'string',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-minus',
};
plus.doc = {
name: 'plus',
description: 'Adds a given period of time to the DateTime',
examples: [
{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.plus(7, 'days')",
evaluated: '[DateTime: 2024-04-07T18:49:00.000Z]',
},
{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.plus(4, 'years')",
evaluated: '[DateTime: 2028-03-30T18:49:00.000Z]',
},
],
section: 'edit',
returnType: 'DateTime',
args: [
{
name: 'n',
description:
'The number of units to add. Or use a Luxon <a target="_blank" href=”https://moment.github.io/luxon/api-docs/index.html#duration”>Duration</a> object to add multiple units at once.',
type: 'number | object',
},
{
name: 'unit',
optional: true,
description:
'The units of the number. One of: <code>years</code>, <code>months</code>, <code>weeks</code>, <code>days</code>, <code>hours</code>, <code>minutes</code>, <code>seconds</code>, <code>milliseconds</code>',
default: '"milliseconds"',
type: 'string',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-plus',
};
diffTo.doc = {
name: 'diffTo',
description: 'Returns the difference between two DateTimes, in the given unit(s)',
examples: [
{
example: "dt = '2025-01-01'.toDateTime()\ndt.diffTo('2024-03-30T18:49:07.234', 'days')",
evaluated: '276.21',
},
{
example:
"dt1 = '2025-01-01T00:00:00.000'.toDateTime();\ndt2 = '2024-03-30T18:49:07.234'.toDateTime();\ndt1.diffTo(dt2, ['months', 'days'])",
evaluated: '{ months: 9, days: 1.21 }',
},
],
section: 'compare',
returnType: 'number | Record<DurationUnit, number>',
args: [
{
name: 'otherDateTime',
default: '$now',
description:
'The moment to subtract the base DateTime from. Can be an ISO date string or a Luxon DateTime.',
type: 'string | DateTime',
},
{
name: 'unit',
default: "'days'",
description:
'The unit, or array of units, to return the result in. Possible values: <code>years</code>, <code>months</code>, <code>weeks</code>, <code>days</code>, <code>hours</code>, <code>minutes</code>, <code>seconds</code>, <code>milliseconds</code>.',
type: 'string | string[]',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-diffTo',
};
diffToNow.doc = {
name: 'diffToNow',
description:
'Returns the difference between the current moment and the DateTime, in the given unit(s). For a textual representation, use <code>toRelative()</code> instead.',
examples: [
{
example: "dt = '2023-03-30T18:49:07.234'.toDateTime()\ndt.diffToNow('days')",
evaluated: '371.9',
},
{
example: "dt = '2023-03-30T18:49:07.234'.toDateTime()\ndt.diffToNow(['months', 'days'])",
evaluated: '{ months: 12, days: 5.9 }',
},
],
section: 'compare',
returnType: 'number | Record<DurationUnit, number>',
args: [
{
name: 'unit',
description:
'The unit, or array of units, to return the result in. Possible values: <code>years</code>, <code>months</code>, <code>weeks</code>, <code>days</code>, <code>hours</code>, <code>minutes</code>, <code>seconds</code>, <code>milliseconds</code>.',
default: "'days'",
type: 'string | string[]',
},
],
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/dates/#date-diffToNow',
};
isEmpty.doc = {
name: 'isEmpty',
description:
'Returns <code>false</code> for all DateTimes. Returns <code>true</code> for <code>null</code>.',
examples: [
{ example: "dt = '2023-03-30T18:49:07.234'.toDateTime()\ndt.isEmpty()", evaluated: 'false' },
{ example: 'dt = null\ndt.isEmpty()', evaluated: 'true' },
],
returnType: 'boolean',
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/arrays/#array-isEmpty',
};
isNotEmpty.doc = {
name: 'isNotEmpty',
description:
'Returns <code>true</code> for all DateTimes. Returns <code>false</code> for <code>null</code>.',
examples: [
{ example: "dt = '2023-03-30T18:49:07.234'.toDateTime()\ndt.isNotEmpty()", evaluated: 'true' },
{ example: 'dt = null\ndt.isNotEmpty()', evaluated: 'false' },
],
returnType: 'boolean',
docURL: 'https://docs.n8n.io/code/builtin/data-transformation-functions/arrays/#array-isNotEmpty',
};
export const dateExtensions: ExtensionMap = {
typeName: 'Date',
functions: {
beginningOf,
endOfMonth,
extract,
isBetween,
isDst,
isInLast,
isWeekend,
minus,
plus,
format,
toDateTime,
diffTo,
diffToNow,
toInt,
toFloat,
toBoolean,
isEmpty,
isNotEmpty,
},
};