当前位置 博文首页 > Baoming ROSE的博客:【Shell笔记】计算某一天距离今天的天数
这段代码并不一定完全正确,而且这段代码计算的只是今天之前的日期距离今天的天数,这段代码只是作为在编写时解决的一些问题的笔记
#!/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 $sub 天
else
((distance+=$cur2))
((distance=${distance}+365-${cur1}))
if `isLeap $year`; then
((distance+=1))
fi
echo $distance 天
fi
eval cur=\${month_days[$i]}
使用了对命令两次扫描,第一次获取数组下标内容,第二次去数组下标对应的内容$变量名
的时候尽量加上{},如果变量名后面连着其他字符,而且没有{},这样就不会取到想要的变量