How to get the date for the last Monday from today?

Hey guys,

I'm looking for an automated way to get the date for the previous Monday from 'today'

So for example if I check now it would return 27-12-2021 and if I run it in 7 days time it would be 03-12-2021 etc etc

Is anyone able to suggest any nodes that may be able to do this that they're aware off or maybe a JS script way to do this?

Using the change node and $moment() in a JSONata expression

[{"id":"21e5e450.ab0664","type":"change","z":"c791cbc0.84f648","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"$moment().isoWeekday(-6)","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":430,"y":440,"wires":[["95b09e83.cfbe38"]]},{"id":"4dd7f307.2c34ec","type":"inject","z":"c791cbc0.84f648","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":220,"y":440,"wires":[["21e5e450.ab0664"]]},{"id":"95b09e83.cfbe38","type":"debug","z":"c791cbc0.84f648","name":"b","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":670,"y":340,"wires":[]}]

expression

$moment().isoWeekday(-6)

[edit] sorry that gets you previous to get the last of the month try

$moment().endOf('month').startOf('isoweek')

I'm sure there may be easier ways using libraries like moment, but in vanilla JavaScript, you can do:

let today = new Date();
let previousMonday = new Date(today.getTime() - (((today.getDay()+6)%7) * 1000*60*60*24))

Let's break that down.

  1. First we get a Date object for today.
  2. today.getDay() gives us the day of week, with 0=Sunday, 1=Monday etc
  3. We can use that value to know how many days to go back to get to the previous Monday. Given its 0 indexed from Sunday, we need to subtract 1 from the value so that 0 is Monday... whilst ensuring that Sunday becomes a 6. That's what this bit of modulo maths does: (today.getDay()+6)%7)
  4. Now we know how many days to go back, we get the current time in milliseconds (today.getTime()), then subtract the right number of days worth of milliseconds (1000*60*60*24)
  5. Finally we create a new Date object from that time.
4 Likes

In the end I used this instead.

$moment().isoWeekday("Monday")

What that be an issue for any reason?

1 Like

Use whichever option you wish.

It's sometimes easier to use a library such as moment, but be aware that 'moment' is being depreciated, and possibly succeeded by a different time/date library in the near future.

Also, you are missing out on a great JavaScript learning experience, which may help you in the future...