Manipulating Time and dates in n8n
Time and dates are some of the key data we use on an almost daily basis. How about when iut comes to n8n, how do we format this data for easy use.
For a while I have been working with n8n and dates and time has been one of the interesting parts on it. I will show you a few tricks you can use in n8n to do quite a few things and manipulations on time and dates using simple code snippets as listed below.
- Filter dates that are not weekends
- Minus time and dates from dates
- Format time and dates to different formats
- Convet time into different timezones
1. Filter weekdays or weekends
For workflows depending on the cron, we may want to have the event run only during the weekdays/ weekends. Here is how
{{ $now.isWeekend }}
This is useful when it comes to calculating days, hours, minutes or even years to or before and event occurs. We can use this eg to calculate how faar a birthday is
- Add 5 days from today
{{ $today.plus({Days: 5}).format("yyyy-MM-dd") }}
- Number of days to August Product launch
{{$today.diff(DateTime.fromISO('2024-08-25'), 'days').toObject().days.toString().substring(1)}}
- What day will 5 days from now be?
{{ $today.plus({Days: 5}).format("EEEE") }}
3. Format time and dates to different formats
Formating time and dates can be useful when presenting it in a human readable format.
Eg,
The default for a command like
{{now}}
is 2024-05-17T17:05:52.414-04:00
This is now the best format when doing workflows like when a meeting was scheduled or planned. A better way could be something like this
Friday, May 17, 2024 {{ $today.format("DDDD") }}
To go around this, you can format your time and date into so many ways
You can copy paste the node below for more formating options
- Simple date type like 2024-05-17
{{ $today.format("yyyy-MM-dd") }}
- May 17, 2024, 12:00 AM
{{ $today.format("ff") }}
4. Convet time into different timezones
Generally, n8n uses the default timezone as America/New York, or EDT.
What happens when you want to use a different timezone eg Nairobi +3 GMT?
OPTION 1: Configure via env
Configure n8n timezone via the enviromnemt. Depending on your hosting platform this will be different
OPTION 2: Set on each workflow
Configure each workflow to use its own timezone directly from the UI on the workflow, via the settings panel. This can affect different if the worklfow depends on another workflow that uses a different timezone
OPTION 3: Use n8n inbuild commands
You can be able to convert timezones on n8n from one to another.
Convert timezone to Nairobi time
{{ DateTime.fromFormat($now.format("yyyy-MM-dd HH:mm:ss"), 'yyyy-MM-dd HH:mm:ss', { zone: 'America/New_York' }).setZone('Africa/Nairobi').toFormat('yyyy-MM-dd HH:mm:ss') }}
With these you can comfortably manage workflows that require time and date manipulation much easily
For more information feel free to email me at [email protected] or website effibotics.com