LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Get first day of last month and last day of last month in bash (https://www.linuxquestions.org/questions/linux-software-2/get-first-day-of-last-month-and-last-day-of-last-month-in-bash-524775/)

KKaushal09 02-03-2015 03:41 AM

Quote:

Originally Posted by xowl (Post 2617397)
Hi, I found a faster way to do this.

I post them here cause it shows how powerful date is:

FirstDay
date -d "-1 month -$(($(date +%d)-1)) days"

Lastday
date -d "-$(date +%d) days -1 month"

Thanks xowl for such interesting answer . There is a correction here for LastDay of previous month:

OUTPUT for
date -d "-$(date +%d) days -1 month"(Lastday) will be the last day of previous to previous month.

So,

FirstDay previous month:
date -d "-1 month -$(($(date +%d)-1)) days"

Lastday previous month:
date -d "-$(date +%d) days"


FirstDay current month:
date -d "-$(($(date +%d)-1)) days"

Lastday current month:
date -d "-$(date +%d) days +1 month"

root03 12-14-2015 01:54 AM

Answered by xowl himself, a little modification though
 
The answer is partly given by @XOWL himself. A little change in that syntax to meet 'DD-MM-YYYY' format :

Eg:
today's date = 14-12-2015
First day of last month = date '+%d-%m-%Y' -d "-1 month -$(($(date +%d)-1)) days" = 01-11-2015
Last day of last month = date '+%d-%m-%Y' -d "-$(date +%d) days" = 30-11-2015

eg 2 : Change of year: If the year changed and moved in to Jan, next year?
today's date (as per example) = 14-01-2016
First day of last month = date '+%d-%m-%Y' -d "-1 month -$(($(date +%d)-1)) days" = 01-12-2015
Last day of last month = date '+%d-%m-%Y' -d "-$(date +%d) days" = 31-12-2015

eg 3 : If the month changed over from Feb?
today's date (as per example) = 03-03-2016
First day of last month = date '+%d-%m-%Y' -d "-1 month -$(($(date +%d)-1)) days" = 01-02-2016
Last day of last month = date '+%d-%m-%Y' -d "-$(date +%d) days" = 29-02-2016
(checked for a leap year) :)


If format needs to be YYYY-MM-DD, then just change date '+%d-%m-%Y' to date '+%F'

PhamTheThao 02-08-2017 10:19 PM

Hi everyone!
I have a bash script and I need it to check current day is 1st day of week or month or quarter or year or not?

This is my format date: #DATE=`date +%u-%d-%m-%Y_%Hh%Mm`

how to check it? thank you!

MensaWater 02-09-2017 10:49 AM

Quote:

Originally Posted by PhamTheThao (Post 5667561)
Hi everyone!
I have a bash script and I need it to check current day is 1st day of week or month or quarter or year or not?

This is my format date: #DATE=`date +%u-%d-%m-%Y_%Hh%Mm`

how to check it? thank you!

Please don't piggy back on old outdated (pun intended) threads. Open a new one instead. You'll get a wider audience on a new thread.


All times are GMT -5. The time now is 10:44 AM.