linux shell循环生成日期

#!/usr/bin/env bash
startDate=$1
endDate=$2
while [ "$startDate" -le "$endDate" ];
do
    desiredDate=`date -d "$startDate" +%Y-%m-%d`
    echo $desiredDate
    startDate=$(date -d "$startDate+1days" +%Y%m%d)
done

执行:

./start.sh 20200101 20200105

结果:
image

时间戳

#!/usr/bin/env bash
startDate=$1
endDate=$2
while [ "$startDate" -le "$endDate" ];
do
    desiredDate=`date -d "$startDate" +%Y-%m-%d`
    echo $desiredDate
    startDT=`date -d "$desiredDate 00:00:00" +"%s%3N"`
         endDT=`date -d "$desiredDate 23:59:59.999" +"%s%3N"`
         echo $startDT $endDT
    startDate=$(date -d "$startDate+1days" +%Y%m%d)
done

执行:

./start.sh 20200101 20200105

结果:
image

分月

#!/usr/bin/env bash
startDate=$1
endDate=$2
while [ "$startDate" -le "$endDate" ];
do
    if [ "${startDate:6:8}" -le "01" ] ; then
        nextMonth=`date -d"$startDate next month" +%Y%m%d`
        lastDay=`date -d"$nextMonth last day" +%Y%m%d`
        beforeDay=`date -d"$nextMonth last month" +%Y%m%d`
        startDT=`date -d "$beforeDay 00:00:00" +"%s%3N"`
        endDT=`date -d "$lastDay 23:59:59.999" +"%s%3N"`
        curMonth=`date -d"$beforeDay" +%Y%m`
        echo $startDT $endDT $curMonth
    fi

    startDate=$(date -d "$startDate+1days" +%Y%m%d)
done

执行:

./start.sh 20200101 20201231

结果:
image

如果觉得我的文章对你有用,请随意赞赏