当前位置 博文首页 > Baoming ROSE的博客:【Shell笔记】计算某一天距离今天的天数

    Baoming ROSE的博客:【Shell笔记】计算某一天距离今天的天数

    作者:[db:作者] 时间:2021-09-12 18:14

    这段代码并不一定完全正确,而且这段代码计算的只是今天之前的日期距离今天的天数,这段代码只是作为在编写时解决的一些问题的笔记

    #!/bin/bash                                                                                                      
                            
    month_days=(0 31 28 31 30 31 30 31 31 30 31 30 31)
            
    # 将当前年月日数字化     
    today_year=`date +"%Y"`
    t_year=`expr $today_year + 0`
    today_month=`date +"%m"`
    t_month=`expr $today_month + 0`
    today_day=`date +"%d"`           
    t_today=`expr $today_day + 0`          
    year=$1                     
    month=$2                     
    day=$3
        
    # 计算是否闰年         
    function isLeap {                       
        if (($1 % 4 == 0 && $1 % 100 != 0 || $1 % 400 == 0)); then
            return 1       
        else
            return 0     
        fi
    }
    
    # 三个参数分别为年月日,计算是当年的第几天
    function cur_days {
        sum=0
        for ((i = 1; i <= $2; ++i)); do
            eval cur=\${month_days[$i]}
            ((sum+=$cur))
        done
        if `isLeap $1` && (($2 > 2)); then
            ((sum+=1))
        fi
        echo $sum
    }
    
    distance=0
    # 计算中间相差年份的天速                                                                                         
    for ((i=$year+1; i<$t_year; ++i)); do
        if `isLeap $i`; then
            ((distance+=366))
        else
            ((distance+=365))
        fi
    done
    
    echo 距离今天有:
    cur1=`cur_days $year $month $day`
    cur2=`cur_days $t_year $t_month $t_day`
    if (($1==$today_year)); then
        ((sub=${cur2} - ${cur1}))
        echo $subelse
        ((distance+=$cur2))
        ((distance=${distance}+365-${cur1})) 
        if `isLeap $year`; then
            ((distance+=1))
        fi
        echo $distancefi
    
    1. 数组只需要空格间隔,不需要逗号或其他符号
    2. date获取的日期字符串前面含0,为了消去0使用t_year=`expr $today_year + 0`将变量转为数字
    3. 对shell的函数的误解:函数返回值只会返回退出吗,函数是一系列命令的集合,如果为了获取到输出,只需要将想要的数据打印即可,然后使用`函数名 参数……`来调用即可。
    4. 而为了获取true或false的就可以利用退出码为0或1作为if的条件
    5. eval cur=\${month_days[$i]}使用了对命令两次扫描,第一次获取数组下标内容,第二次去数组下标对应的内容
    6. $变量名的时候尽量加上{},如果变量名后面连着其他字符,而且没有{},这样就不会取到想要的变量
    cs