A CLI command to output the previous month on macOS (BSD)


I wanted to create a variable/placeholder that would take the current month, and output last month in the format “Month Year”. I reached out on Discord, and received some helpful suggestions. Unfortunately they didn’t help me achieve what I was aiming for.

The solution

This morning one of my colleagues gave me a simple command that works well on macOS. I didn’t realise that macOS’ base is BSD, so GNU commands like date --date='-30 days' won’t work for me.

The initial solution my colleague shared was this: date -v-30d. This produces the following based on today being Mon Feb 15 09:28:58 IST 2021:

Sat Jan 16 09:28:37 IST 2021

I took a look at the man pages for the date command, and adapted one of the examples to give me what I need:

date -v-30d -j -f "%a %b %d %T %Z %Y" "`date`" "+%B %Y"

My colleague shared a more refined version that produces the same output:

date -v-30d +'%B %Y'

The output for this command is January 2021 - pretty much what I needed.

Minor challenge

I’d like to be able to add this to a general template, with the command being inserted using Templater. Unfortunately, it looks like the Templater template doesn’t render when I apply the note template containing it to a new, blank note.

Instead, I have to add the note template directly from Templater for it to render correctly for me. It works, it’s just a bit slow.

1 Like

If it helps, you can install coreutils (brew install coreutils if you use homebrew) and have ‘gdate’ as the GNU date…

I use:

/usr/local/bin/gdate --date=“last month” +"%Y-%m %B"

1 Like