De DateTime node is de tijdmeester van N8N - een essentiële node voor elke workflow die met datums en tijden werkt. Van simpele datum formatting tot complexe timezone conversies en business day berekeningen, deze node biedt alle tools die je nodig hebt voor professionele tijd manipulatie.
In deze uitgebreide gids duiken we diep in de DateTime node en de krachtige Luxon library die eronder ligt, zodat je nooit meer worstelt met datum en tijd problemen in je workflows.
Wat is de DateTime Node?
De DateTime node is een data transformatie node gespecialiseerd in het manipuleren van datum en tijd data. Deze node kan:
- Formatteren: Converteer tussen verschillende datum formaten
- Berekenen: Voeg tijd toe of trek af, bereken verschillen
- Extraheren: Haal specifieke delen uit een datum (jaar, maand, dag, etc.)
- Timezone conversie: Converteer tussen verschillende tijdzones
- Business logic: Check weekends, werkdagen, kwartalen
- Validatie: Controleer of datums geldig zijn
Belangrijke kenmerken:
- Luxon-powered: Gebruikt de robuuste Luxon library onder de motorkap
- Timezone-aware: Respecteert workflow en instance timezone settings
- ISO 8601 support: Native ondersteuning voor ISO datum standards
- Locale support: Ondersteunt Nederlandse datum formats
- Expression compatible: Werkt naadloos met N8N expressions
Core Operations in Detail
1. Format a Date 📅
Converteer datums tussen verschillende formaten - de meest gebruikte operatie.
| Format Token | Output | Voorbeeld |
|---|---|---|
dd-MM-yyyy |
Nederlandse datum | 03-01-2025 |
yyyy-MM-dd |
ISO datum | 2025-01-03 |
dd LLLL yyyy |
Volledige naam | 03 januari 2025 |
HH:mm:ss |
24-uurs tijd | 14:30:45 |
EEEE |
Weekdag naam | vrijdag |
W |
Week nummer | 1 |
// DateTime node configuratie
{
"operation": "formatDate",
"date": "{{ $json.orderDate }}", // Input: 2025-01-03T14:30:00Z
"format": "custom",
"customFormat": "dd-MM-yyyy HH:mm",
"outputFieldName": "formattedDate" // Output: 03-01-2025 14:30
}
2. Add to a Date ➕
Voeg tijd toe aan een bestaande datum - perfect voor deadlines en reminders.
// Verschillende tijd toevoegingen
{
"operation": "addToDate",
"magnitude": 7,
"timeUnit": "days",
"date": "{{ $json.startDate }}",
"outputFieldName": "deadline"
}
// Complexere berekeningen met expressions
{{ DateTime.fromISO($json.date).plus({
days: 7,
hours: 2,
minutes: 30
}).toISO() }}
3. Get Time Between Dates ⏱️
Bereken het verschil tussen twee datums - essentieel voor SLA tracking en leeftijd berekeningen.
// DateTime node configuratie
{
"operation": "getTimeBetweenDates",
"startDate": "{{ $json.orderDate }}",
"endDate": "{{ $json.deliveryDate }}",
"unit": "days", // of: hours, minutes, seconds, months, years
"outputFieldName": "deliveryTime"
}
// Met Luxon expression voor precisie
{{
DateTime.fromISO($json.endDate)
.diff(DateTime.fromISO($json.startDate), ['days', 'hours'])
.toObject()
}}
// Output: { days: 5, hours: 3 }
4. Extract Date Part 🔍
Haal specifieke componenten uit een datum - handig voor rapportages en groepering.
| Part | Output | Use Case |
|---|---|---|
| Year | 2025 | Jaarlijkse rapportages |
| Month | 1 | Maandelijkse groepering |
| Week | 1 | Weekly reports |
| Day | 3 | Dagelijkse taken |
| Hour | 14 | Uurlijke batches |
| Weekday | 5 (vrijdag) | Weekend checks |
5. Get Current Date 📍
// Get current timestamp
{
"operation": "getCurrentDate",
"includeTime": true, // Include time or set to midnight
"outputFieldName": "timestamp"
}
// In expressions
{{ $now }} // Luxon DateTime object
{{ $today }} // Today at midnight
{{ $now.toISO() }} // ISO string: 2025-01-03T14:30:00.000Z
Timezone Management
Timezone handling is cruciaal voor internationale workflows. N8N gebruikt een hiërarchie voor timezone bepaling:
Timezone Conversie Voorbeelden
// Convert UTC to Amsterdam time
{{ DateTime.fromISO($json.utcDate, {zone: 'utc'})
.setZone('Europe/Amsterdam')
.toISO() }}
// Get current time in different timezones
const now = DateTime.now();
const timezones = {
amsterdam: now.setZone('Europe/Amsterdam').toFormat('HH:mm'),
london: now.setZone('Europe/London').toFormat('HH:mm'),
newYork: now.setZone('America/New_York').toFormat('HH:mm'),
tokyo: now.setZone('Asia/Tokyo').toFormat('HH:mm')
};
// Check if datetime is in DST (Daylight Saving Time)
{{ DateTime.fromISO($json.date)
.setZone('Europe/Amsterdam')
.isInDST }}
Nederlandse Timezone Tips:
- Nederland: Gebruik altijd
Europe/Amsterdam - België: Gebruik
Europe/Brussels - DST: Automatisch gehandeld (CET ↔ CEST)
- Offset: UTC+1 (winter) / UTC+2 (zomer)
Luxon Power Features
De Luxon library onder de DateTime node biedt geavanceerde functionaliteit:
Business Day Calculations
// Check if date is weekend
{{ DateTime.fromISO($json.date).weekday > 5 }}
// weekday: 1 = Monday, 7 = Sunday
// Get next business day
const getNextBusinessDay = (date) => {
let nextDay = DateTime.fromISO(date).plus({days: 1});
while (nextDay.weekday > 5) {
nextDay = nextDay.plus({days: 1});
}
return nextDay.toISO();
};
// Calculate business days between dates
const getBusinessDays = (start, end) => {
let current = DateTime.fromISO(start);
const endDate = DateTime.fromISO(end);
let businessDays = 0;
while (current <= endDate) {
if (current.weekday <= 5) {
businessDays++;
}
current = current.plus({days: 1});
}
return businessDays;
};
Quarter and Fiscal Year
// Get quarter
{{ Math.ceil(DateTime.fromISO($json.date).month / 3) }}
// Get fiscal year (starting April)
const getFiscalYear = (date) => {
const dt = DateTime.fromISO(date);
return dt.month >= 4 ? dt.year : dt.year - 1;
};
// Get quarter dates
const getQuarterDates = (year, quarter) => {
const startMonth = (quarter - 1) * 3 + 1;
return {
start: DateTime.fromObject({year, month: startMonth, day: 1}).toISO(),
end: DateTime.fromObject({year, month: startMonth + 2, day: 1})
.endOf('month').toISO()
};
};
Relative Time Calculations
// Human-readable relative time
{{ DateTime.fromISO($json.date).toRelative() }}
// Output: "2 days ago", "in 3 hours", etc.
// Start/end of period
{{ DateTime.fromISO($json.date).startOf('month').toISO() }}
{{ DateTime.fromISO($json.date).endOf('week').toISO() }}
{{ DateTime.fromISO($json.date).startOf('day').toISO() }}
// Age calculation
{{ Math.floor(
DateTime.now().diff(
DateTime.fromISO($json.birthDate), 'years'
).years
) }}
Praktische Use Cases
Use Case 1: SLA Deadline Monitoring
// SLA deadline calculation workflow
const ticket = $json;
const created = DateTime.fromISO(ticket.createdAt);
const priority = ticket.priority;
// SLA times in business hours
const slaHours = {
'critical': 4,
'high': 8,
'medium': 24,
'low': 48
};
// Calculate deadline (skip weekends)
let deadline = created;
let hoursToAdd = slaHours[priority];
while (hoursToAdd > 0) {
deadline = deadline.plus({hours: 1});
// Skip if weekend or outside business hours (9-17)
if (deadline.weekday <= 5 &&
deadline.hour >= 9 &&
deadline.hour < 17) {
hoursToAdd--;
}
}
return {
ticketId: ticket.id,
created: created.toISO(),
deadline: deadline.toISO(),
remaining: deadline.diff(DateTime.now(), 'hours').hours,
isOverdue: DateTime.now() > deadline
};
Use Case 2: Recurring Event Generator
// Generate recurring events
const generateRecurring = (startDate, frequency, count) => {
const events = [];
let current = DateTime.fromISO(startDate);
for (let i = 0; i < count; i++) {
events.push({
eventDate: current.toISO(),
eventDay: current.toFormat('EEEE'),
eventWeek: current.weekNumber,
formattedDate: current.toFormat('dd-MM-yyyy HH:mm')
});
// Add based on frequency
switch(frequency) {
case 'daily':
current = current.plus({days: 1});
break;
case 'weekly':
current = current.plus({weeks: 1});
break;
case 'monthly':
current = current.plus({months: 1});
break;
case 'quarterly':
current = current.plus({months: 3});
break;
}
}
return events;
};
// Usage
return generateRecurring($json.startDate, 'weekly', 10);
Use Case 3: Working Hours Calculator
// Calculate working hours between timestamps
const calculateWorkingHours = (start, end) => {
const startDT = DateTime.fromISO(start);
const endDT = DateTime.fromISO(end);
let current = startDT;
let workingMinutes = 0;
while (current < endDT) {
// Check if weekday (Mon-Fri)
if (current.weekday <= 5) {
// Check if within working hours (9-17)
const hour = current.hour;
if (hour >= 9 && hour < 17) {
workingMinutes++;
}
}
current = current.plus({minutes: 1});
}
return {
totalHours: Math.round(workingMinutes / 60 * 100) / 100,
totalDays: Math.round(workingMinutes / 480 * 100) / 100,
formatted: `${Math.floor(workingMinutes/60)}h ${workingMinutes%60}m`
};
};
Common Date Patterns
Nederlandse Datum Formats
| Pattern | Format String | Output |
|---|---|---|
| Kort | dd-MM-yyyy |
03-01-2025 |
| Lang | d MMMM yyyy |
3 januari 2025 |
| Met tijd | dd-MM-yyyy HH:mm |
03-01-2025 14:30 |
| Weekdag | EEEE d MMMM |
vrijdag 3 januari |
| ISO week | kkkk-'W'WW |
2025-W01 |
Validation Patterns
// Validate date string
const isValidDate = (dateString, format) => {
try {
const dt = format
? DateTime.fromFormat(dateString, format)
: DateTime.fromISO(dateString);
return dt.isValid;
} catch (e) {
return false;
}
};
// Check if date is in the past
{{ DateTime.fromISO($json.date) < DateTime.now() }}
// Check if date is within range
const isInRange = (date, startDate, endDate) => {
const dt = DateTime.fromISO(date);
const start = DateTime.fromISO(startDate);
const end = DateTime.fromISO(endDate);
return dt >= start && dt <= end;
};
Integration met Andere Nodes
Schedule Trigger + DateTime
Combineer met Schedule Trigger voor tijdgebaseerde workflows:
// Check if today is last day of month
{{ DateTime.now().endOf('month').day === DateTime.now().day }}
// Run only on weekdays
{{ DateTime.now().weekday <= 5 }}
Wait Node + DateTime
Gebruik met Wait Node voor dynamische delays:
// Wait until next Monday 9 AM
const nextMonday = DateTime.now()
.plus({weeks: DateTime.now().weekday === 1 ? 1 : 0})
.set({weekday: 1, hour: 9, minute: 0, second: 0});
const waitSeconds = nextMonday.diff(DateTime.now(), 'seconds').seconds;
Best Practices & Performance
Performance Tips:
- Parse once: Parse datum strings één keer en hergebruik het DateTime object
- Use ISO format: ISO 8601 is het snelst te parsen
- Cache calculations: Bewaar berekende waarden in Set node
- Batch operations: Gebruik Code node voor bulk operations
- Timezone consistency: Werk intern in UTC, converteer alleen voor display
Common Pitfalls
| Probleem | Oorzaak | Oplossing |
|---|---|---|
| Verkeerde timezone | Impliciete conversie | Gebruik expliciete setZone() |
| Invalid date errors | Wrong format string | Check format met isValid |
| DST issues | Manual offset calc | Gebruik timezone names |
| Off-by-one errors | Weekday confusion | Remember: 1=Mon, 7=Sun |
Advanced DateTime Patterns
Holiday Detection
// Nederlandse feestdagen checker
const isDutchHoliday = (date) => {
const dt = DateTime.fromISO(date);
const year = dt.year;
// Vaste feestdagen
const fixedHolidays = [
`${year}-01-01`, // Nieuwjaar
`${year}-04-27`, // Koningsdag
`${year}-12-25`, // Eerste Kerstdag
`${year}-12-26` // Tweede Kerstdag
];
// Check if date matches
const dateStr = dt.toFormat('yyyy-MM-dd');
if (fixedHolidays.includes(dateStr)) return true;
// Pasen berekening (simplified)
// Add logic for Easter, Pentecost, etc.
return false;
};
Batch Date Processing
// Process multiple dates efficiently
const processDates = $input.all().map(item => {
const dt = DateTime.fromISO(item.json.date);
return {
json: {
...item.json,
formatted: dt.toFormat('dd-MM-yyyy'),
weekday: dt.weekday,
weekdayName: dt.toFormat('EEEE'),
week: dt.weekNumber,
month: dt.month,
quarter: Math.ceil(dt.month / 3),
year: dt.year,
isWeekend: dt.weekday > 5,
isToday: dt.hasSame(DateTime.now(), 'day'),
isPast: dt < DateTime.now(),
daysFromNow: Math.floor(dt.diff(DateTime.now(), 'days').days)
}
};
});
return processDates;
Troubleshooting Guide
Debug Strategies:
- Gebruik
.toObject()om alle date components te zien - Check
.isValiden.invalidReasonbij problemen - Log timezone met
.zoneNameen.offset - Test met
.toISO()voor debugging - Gebruik
.toMillis()voor timestamp comparisons
Conclusie en Next Steps
De DateTime node is een onmisbare tool voor elke serieuze N8N workflow. Met de kracht van Luxon onder de motorkap kun je elke datum/tijd uitdaging aan - van simpele formatting tot complexe business logic met timezones.
Key Takeaways
- 5 Core Operations: Format, Add, Subtract, Extract, Current
- Luxon Power: Gebruik expressions voor advanced features
- Timezone Hierarchy: Node → Workflow → Instance
- Nederlandse Formats:
dd-MM-yyyyis de standaard - Business Logic: Weekday checks, working hours, holidays
- Performance: Parse once, use ISO, work in UTC
- Integration: Combineer met Schedule, Wait, Code nodes
Veelgestelde Vragen
Hoe zet ik Amerikaanse datum (MM/DD/YYYY) om naar Nederlandse?
Gebruik: DateTime.fromFormat($json.usDate, 'MM/dd/yyyy').toFormat('dd-MM-yyyy')
Hoe bereken ik iemands leeftijd?
Gebruik: Math.floor(DateTime.now().diff(DateTime.fromISO($json.birthDate), 'years').years)
Kan ik recurring events genereren?
Ja! Gebruik een loop met .plus() om herhalende datums te genereren op basis van interval.
Hoe handel ik DST (zomertijd/wintertijd) af?
Gebruik altijd timezone namen zoals 'Europe/Amsterdam' - Luxon handelt DST automatisch af.
Deze gids wordt regelmatig bijgewerkt met nieuwe DateTime features en patterns. Bookmark deze pagina voor de laatste datum/tijd best practices in N8N.