Issue
I need to calculate the current, previous and next year quarter from the current sysdate in the below format.
As per current date (02-Nov-2020), current quarter should be returned as 20204
, previous quarter as 20203
, next quarter as 20211
. It should be dynamic and should work for all the date/ month. I am trying with some approach like below but it doesn't seems to be working. Please help me with this. Thanks in advance.
curr_yrqtr=$(date +%Y)$(( ($(date +%-m)-1)/3+1 ))
prev_yrqtr=$(date -d "-1 month" +%Y)$(( ($(date -d "-1 month" +%-m)-1)/3+1 ))
Solution
Seeing how the question has several different flags (bash
, ksh
, perl
), I'm guessing the OP is open to any solution that generates the desired results.
If the OP's version of date
includes support for the %q
(quarter) format:
read -r curr_year curr_qtr < <(date '+%Y %q')
If the OP's version of date
does not support the %q
(quarter) format:
read -r curr_year curr_month < <(date '+%Y %m')
curr_qtr=$((curr_month / 3 + 1))
From here the rest of the code is the same regardless of the version of date
:
prev_year="${curr_year}"
prev_qtr=$((curr_qtr - 1))
next_year="${curr_year}"
next_qtr=$((curr_qtr + 1))
case "${curr_qtr}" in
1) prev_year=$((curr_year - 1)) ; prev_qtr=4 ;;
4) next_year=$((curr_year + 1)) ; next_qtr=1 ;;
esac
echo "previous quarter : ${prev_year}${prev_qtr}"
echo "current quarter : ${curr_year}${curr_qtr}"
echo "next quarter : ${next_year}${next_qtr}"
Running the above where 'today' == 2 Nov 2020:
previous quarter : 20203
current quarter : 20204
next quarter : 20211
Answered By - markp-fuso