date打印指定的时间段YYYYMMDD

2014-03-26

有时我们需要生成一段时间内的YYYYMMDD格式的字符串。

方法1:利用unix时间戳
#!/bin/bash
#date.sh

beg_date=`date -d "$1" +%s`
end_date=`date -d "$2" +%s`

if [[ -z $1 ]]||[[ -z $2 ]];then
echo "Usage: $0 YYYYMMDD YYYYMMDD"
exit 0;
fi

if [[ ${beg_date} > ${end_date} ]];then
echo "The end_date < beg_date ;Please input the right date,example 20140101 20140301"
exit 0;
fi

for (( i=${beg_date};i<=${end_date};i=i+86400))

do

date -d @${i} +%Y%m%d

done

##############################################################

或者将for替换为While

while [ "$beg_date" -le "$end_date" ]

do date -d @${beg_date} +%Y%m%d

beg_date=$((beg_date+86400))

done 方法

2:利用date +%Y%m%d -d 20140101" +1 days"

#!/bin/sh

beg_date=$1

end_date=$2

i=1

if [[ -z $1 ]]||[[ -z $2 ]];then

echo "Usage: $0 YYYYMMDD YYYYMMDD"

exit 0;

fi

if [[ ${beg_date} > ${end_date} ]];then
echo "The end_date < beg_date ;Please input the right date,example 20140101 20140301"
exit 0;
fi

while [[ ${beg_date} -le ${end_date} ]];
do
echo $beg_date;
beg_date=`date +%Y%m%d -d ${beg_date}" ${i} days"`
i=i+1
done

####################################################################
./date 20140227 20140305
20140227
20140228
20140301
20140302
20140303
20140304

其他:只打印YYYYMM年月
#!/bin/sh

. ~/.bash_profile

beg_date=37
end_date=45

for (( i=${beg_date};i<=${end_date};i++))
do
j=$(expr $i \* -1)
ym=`date -d ${j}month +%Y%m`
sqlplus 'data/data123456' << EOF
truncate table CHAT_${ym};
drop table CHAT_${ym} purge;
DROP TABLESPACE CHAT_DATA_TD_${ym} INCLUDING CONTENTS AND DATAFILES;
EOF
done

分类:Linux编程 | 标签: |

相关日志

评论被关闭!