date_before_seasons.sh
#!/usr/bin/env bash
:<<describle
desc: 获取指定日期的前N个季度的日期
author: Answer.AI.L
datetime: 2019-09-11 16:17:39
params: report_dt 日期, 格式:yyyy-mm-dd
reasons 返回N个前移的季度
describle
# set -x
# 日期, 默认当前日期, 格式: yyyy-mm-dd
[ $1 ] && date=$1 || date=`date +%Y-%m-%d`
# 返回N个前移的季度
[ $2 ] && rltCnt=$2 || rltCnt=4
# 返回N个季度信息的数组
rtnSeasons=()
:<<comments
获取指定date的前rltCnt个季度信息
@param date
@param rltCnt
comments
function dateBeforSeasons(){
# 注意该字段为全局变量, 每次使用需要清空数组
unset rtnSeasons
local date=$1
local rltCnt=$2
echo "calculate date: "${date}
# 把日期中的-字符全部替换为空格
date=${date//-/}
# 从第4位开始截取date字符串并对其进行转为数字
local dt=`expr ${date:4} + 0`
local year=${date:0:4}
local ruleArr=(101'<='${dt}'&'${dt}'<='301 401'<='${dt}'&'${dt}'<='630 701'<='${dt}'&'${dt}'<='930 1001'<='${dt}'&'${dt}'<='1231)
# 季节数组, 01010331 -> 第一季节
local seasonArr=('01010331' '04010630' '07010930' '10011231')
local nowSeason=0
for (( i=0; i<${#ruleArr[@]}; i++ ))
do
# 判断当前月份所属的季度
if [ $[${ruleArr[i]}] -eq 1 ];then
nowSeason=${i};
break
fi
done
#echo ${date}"属于第"${nowSeason}"季度"
# 取当前季度的上一个季度
let nowSeason--
for (( i=0; i<${rltCnt}; i++ ))
do
# 如果当前季度小于0(0为第一季度), 则年份前推一年
if [ ${nowSeason} -lt 0 ]; then
let year--
let nowSeason+=4
fi
local index=$((nowSeason%4))
local prevmd=${seasonArr[index]:0:4}
local nextmd=${seasonArr[index]:4}
local prev_month=${prevmd:0:2}
local prev_day=${prevmd:2}
local next_month=${nextmd:0:2}
local next_day=${nextmd:2}
rtnSeasons[i]=${year}"-"${prev_month}"-"${prev_day}"~"${year}"-"${next_month}"-"${next_day}
let nowSeason--
done
echo "date: "$1", cnt: "${rltCnt}" -> rtnSeasons: "${rtnSeasons[@]}
}
dateBeforSeasons 2019-09-11 8
echo "rlt: "${rtnSeasons[@]}
:<<test 测试
dateBeforSeasons ${date} ${rltCnt}
echo "rtnSeasons length: "${#rtnSeasons[*]}
for v in ${rtnSeasons[@]}
do
echo ${v}
done
dateBeforSeasons 2019-09-11 8
echo "rlt: "${rtnSeasons[@]}
test
# set +x
获取 2019-09-11的前8个季度的起止日期
dateBeforSeasons 2019-09-11 8
2019-04-01~2019-06-30 2019-01-01~2019-03-31 2018-10-01~2018-12-31 2018-07-01~2018-09-30
2018-04-01~2018-06-30 2018-01-01~2018-03-31 2017-10-01~2017-12-31 2017-07-01~2017-09-30