bash: How to get first and last dates of previous month
I had a task that i needed to calculate some data between the first and the last date of the previous month, bash is powerful and provides…
I had a task that i needed to calculate some data between the first and the last date of the previous month, bash is powerful and provides an easy way to do such calculations avoiding any pitfalls that come up when dealing with dates.
Lets calculate the first day of the previous month$ date --date="$(date +'%Y-%m-01') - 1 month" +%Y-%m-%d
2021-09-01
How it works:
We are calculating the first day of the current month and we subtracting one month.
- date: the command that generates timestamps
- - date : this is tricky! this option allows to do calculations between the dates, everything between $(<expression>) is calculated by bash, so in this case
date '%Y-%m-01' — 1 monthasks from date to calculate the date between2021-10-01 — 1 Month%Y-%m Are substituted by current year and month. - +%Y-%m-%d is the output format
Lets calculate now the last day of the previous month
We are calculating the first day of the current month and we subtracting just one second, this is enough to give us the last day of the previous month!$ date --date="$(date +'%Y-%m-01') - 1 second" +%Y-%m-%d
2021-09-30
I will not get into much details since the logic is the same like calculating the first date of the month and i thing that is crystal clear how it works!
I hope you found this article useful :)