Script for the last day of the month

Hi everyone, could you please kindly help me on this?

  1. is there any script to take the last day of the month?
    For example in below picture, current month is Jun. So i want day will be 30. if Feb, output is 28, or output is 31 for Mar
  2. In case the last date of the month is on Sat or Sun, is there any script to set the last date of the month on working day (Mon-Fri) only.

Check it out:

Be aware that you need to add the following env variable:
- NODE_FUNCTION_ALLOW_EXTERNAL=moment

Warm,
Simon

1 Like

thanks a lot for your guideline.
Could you guide me more where i should put the Fuction2 node in this workflow

Share your WF I’ll edit it for you,
You should add it before the node where you gonna to use it and bind it via expression :wink:

For simplicity sake I’d suggest using the inbuilt Luxon library that ships with more recent n8n versions. This avoids importing functions with NODE_FUNCTION_ALLOW_EXTERNAL.

To get the last day of the month you could use this in an expression
{{ $today.set({ day: 1 }).plus({ months: 1 }).minus({days: 1}).toISODate() }}

2 Likes

@pemontto thks a lot. how can i change it to this format
image

your current output is like this


and if the last day is on weekends, How can i set up so that it move to Fri? the format i need just MM/DD/YYYY?

how can i do this like you?

Hi @H_nh_Nguy_n, you can format dates by replacing .toISODate() with .toFormat('L/d/yyyy'). Check out this list for all tokens you can use in .toFormat().

To preview a workflow simply select and copy your workflow from the n8n canvas and then paste it here on the forum using the preformatted text option on a new empty line:

Thanks a lot for your support!! i can change the format now

@MutedJam Could you help me if the last day is on weekends, How can i set up so that it move to Fri? the format i need just MM/DD/YYYY?

Here’s a verbose function that should show you how it can be done:

You can also use this :

{{ $now.endOfMonth().format(‘yyyy-MM-dd’) }}

1 Like

how to get the first day of the month?

Hey @marat,

Welcome to the community :tada:

Quickest option would be the below which will always set the day of the current month to 1.

{{ $today.set({ day: 1 }).toISODate() }}

What if I want to filter for last month for this formate: 2024-07-01 00:00:00?
Can we do it with expression only?

Hi @Lucifer,

Welcome to the community :tada:

not sure if this is what you’re asking for, but if you want to filter or select dates that fall within the last month, here’s one way of doing it:
start of last month:

{{ $today.minus({ months: 1 }).startOf('month').toFormat('yyyy-MM-dd HH:mm:ss')}}

end of last month:

{{ $today.minus({ months: 1 }).endOf('month').toFormat('yyyy-MM-dd HH:mm:ss')}}
1 Like

Thanks @aya :innocent:

1 Like