【问题标题】:Korn Shell Increment Date in YYYYMMDD formatYYYYMMDD 格式的 Korn Shell 增量日期
【发布时间】:2020-04-26 08:56:12
【问题描述】:

我需要增加具有特定格式 YYYYMMDD 的日期(例如:20190401 或 20190523)。 0 必须存在一位数的日期和月份。

我想要输入 cmd 行参数 ex ./script.ksh(增加的天数)(开始日期)或 ./script.ksh(开始日期)(结束日期)

我制作了一个糟糕的版本,包含 ./script.ksh (# of days) (year) (month) (day) ex: ./script.ksh 7 2019 04 10

#The amount of days to load by
Days=$1

Year=$2
Month=$3
Day=$4

count=0

while (($count < $Days)) 
do
    #The date of the file in format: YYYYMMDD
    if [[ $Day -eq "1" || $Day -eq "2" || $Day -eq "3" || $Day -eq "4" || $Day -eq "5" || $Day -eq "6" || $Day -eq "7" || $Day -eq "8" || $Day -eq "9" ]];
    then
        Day=0$Day
    fi

    Date=$Year$Month$Day
    print $Date

    #Check if month then day and increment accordingly

    #months with 31 days
    if [[ ($Month -eq "01" || $Month -eq "03" || $Month -eq "05" || $Month -eq "07" || $Month -eq "08" || $Month -eq "10" || $Month -eq "12") && ($Day == 31)]];
        then
                #If Dec, 31 XXXX
                if [[ $Month -eq "12" && Day == 31 ]];
                then
                        Month=01
                        Day=01
                        Year=$Year+1
                fi
                if((Day == 31));
                then
                        Month=$Month+1
                        Day=1
                fi
        #Months with 30 days
        elif [[ ($Month -eq "04" || $Month -eq "06" || $Month -eq "09" || $Month -eq "11") && ($Day == 30) ]];
        then
                if(($Day == 30));
                then
                        $Month=$Month+1
                        Day=01
                fi
        #The tricky February leap year
        elif [[ ($Month -eq "02") && ($Day == 28 || $Day == 29) ]];
        then
                leapcheck=$(($Year % 4))
                if(( leapcheck == 0 && Day == 29 ));
                then
                        Month=$Month+1
                        Day=01

                elif(( $leapcheck != 0  && $Day == 28 ));
                then
                        Month=$Month+1
                        Day=01
                fi
        else
                (( Day=$Day+1 ))
        fi

        ((count=$count+1))
done

这将打印 20190410 到 20190416。但是,增加月份和日期存在问题,其中 0 被删除,而我的月份根本不增加。我敢肯定,一定有比我的尝试更简单、更好的方法。我是 korn shell 脚本的新手。

【问题讨论】:

  • 您是否有一个版本的date 命令(例如 GNU 版本)可以让您相对轻松地完成这项工作?你考虑过那个选项吗?如果做不到这一点,您能否使用 Perl 或其他脚本语言,以及使计算变得容易的内置或扩展模块?

标签: shell unix ksh


【解决方案1】:

如果您有date(带有-d 选项),一个简单的方法是将日期转换为自纪元以来的秒数,添加以秒为单位的天数,然后将其转换回格式你想要的:

days=5
now=20190401

now_sec=$(date -d "${now:0:4}-${now:4:2}-${now:6:2} 11:00:00" +%s)
then_sec=$((now_sec + days * 3600 * 24))
then=$(date -d @"$then_sec" +%Y%m%d)

echo "$then" # will output 20190406

${now:0:4} 提取字符串的一部分,参见parameter expansions

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2017-05-12
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多