【问题标题】:How can I loop for end of month date between to dates in sh?如何在 sh 中循环到日期之间的月末日期?
【发布时间】:2021-02-18 20:06:34
【问题描述】:

我想在两个日期之间循环打印月末日期。

我有以下代码,但它每天都在打印。

startdate='2021-01-01'
enddate='2021-04-01'

enddate=$( date -d "$enddate + 1 day" +%Y%m%d )   # rewrite in YYYYMMDD format
                                                  #  and take last iteration into account
thedate=$( date -d "$startdate" +%Y%m%d )
while [ "$thedate" != "$enddate" ]; do
    printf 'The date is "%s"\n' "$thedate"
    thedate=$( date -d "$thedate + 1 days" +%Y%m%d ) # increment by one day
done

但我希望这些结果用于:

  startdate='2021-01-01'
    enddate='2021-04-01'

20210131

20210228

20210331

提前致谢

【问题讨论】:

    标签: linux bash shell unix


    【解决方案1】:

    类似的东西

        year=$(date +%Y)
    for month in {01..04}; {
        day=($(cal -d $year-$month))
        echo "$year$month${day[@]:(-1)}"
    }
    20210131
    20210228
    20210331
    20210430
    

    或使用 -m 标志

    year=$(date +%Y)
    for month in {01..04}; {
        day=($(cal -m $month $year))
        echo "$year$month${day[@]:(-1)}"
    }
    20210131
    20210228
    20210331
    20210430
    

    【讨论】:

    • cal 的哪个版本支持-d 标志?我的cal 是 2.33.1 并且没有。
    • 我有 gnome-calendar 3.36.1-linuxmint1
    【解决方案2】:

    使用date 命令:

    #!/usr/bin/env bash
      
    startdate=$1
    enddate=$2
    
    while true; do
        month_end=$(date -d "${startdate::6}01 +1month -1day" +%Y%m%d)
        [[ $month_end -lt $enddate ]] && echo $month_end || break
        startdate=$(date -d "$month_end +1day" +%Y%m%d)
    done
    

    调用方法

    $ ./test.sh 20210101 20210401
    20210131
    20210228
    20210331
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多