How to generate a year-quarter date from the command line?
One (kinda ugly) solution, using BASH arithmetic evaluation and the GNU date
command:
echo $(date +%Y)q$(( ($(date +%-m)-1)/3+1 ))
echo $(date -d "-1 month" +%Y)q$(( ($(date -d "-1 month" +%-m)-1)/3+1 ))
Note that the %-m
prevents date
from 0-padding,
so this will still work for August and September.
Use my dateutils:
dconv 2012-01-01 -f '%Y%Q'
=>
2012Q1
The %q
and %Q
flags are specific to dateutils, and return the quarter as number or in the form Q<NUMBER>
.
All solutions that divide by four fail, for instance November:
% echo $(( 11/4+1 ))
3
The correct math would be:
$(( (m-1)/3 +1 ))
And as such, the quarter of current and previous month would be:
echo curr ${y}q$(((m-1)/3+1))
if [ $m = 1 ]; then
echo prev $((y-1))q4
else
echo prev ${y}q$(((m-2)/3+1))
fi
It's only twelve values to check, really…
% for m in {1..12}; do echo $m Q$(((m-1)/3+1)); done
1 Q1
2 Q1
3 Q1
4 Q2
5 Q2
6 Q2
7 Q3
8 Q3
9 Q3
10 Q4
11 Q4
12 Q4