计算两个日期相差多少天数的shell/ target=_blank class=infotextkey>shell脚本,很不错,有需要的朋友不妨参考下。
#!/bin/bash
#the days between your input and today!
#2012-10-07
year(){
while read -p "please input the year(must be YYYY ): " YEAR
do
if ((YEAR>=1990)) && ((YEAR<=9999));then
echo $YEAR
break
fi
done
}
month(){
while read -p "please input the month (must be MM ): " MONTH
do
MONTH_TMP=`echo ${MONTH/0/}`
if ((MONTH_TMP<=12)) && ((MONTH_TMP>=1)) && [[ `expr length $MONTH` -eq 2 ]];then
echo $MONTH
break
fi
done
}
day(){
while read -p "please input the day (must be dd ): " DAY
do
DAY_TMP=`echo ${DAY/0/}`
if ((DAY_TMP<=31)) && ((DAY_TMP>=1)) && [[ `expr length $DAY` -eq 2 ]];then
echo $DAY
break
fi
done
}
ARISE(){
while :
do
((++num))
TMP_DATE=$(date -d "$num days " +%F| sed -e 's/-//g')
if [[ $TMP_DATE -eq $2 ]];then
break
fi
done
return $num
}
DRISE(){
while :
do
((++num))
TMP_DATE=$(date -d "$num days ago" +%F| sed -e 's/-//g')
if [[ $TMP_DATE -eq $2 ]];then
break
fi
done
return $num
}
#判定用户输入的日期的合法性,包括(该日期是否存在,输入的格式是否正确)
while :
do
USER_YEAR=`year`
USER_MONTH=`month`
USER_DAY=`day`
USER_DATE="${USER_YEAR}${USER_MONTH}${USER_DAY}"
CUR_DATE=`date +'%F' | sed -e 's/-//g'`
exist_day=`cal $USER_MONTH $USER_YEAR | sed -n -e '7s/.*(..)$/1/p'`
if [[ $exist_day -lt ${USER_DAY/0/} ]];then
echo "this $USER_DATE is not exist!!!"
else
break
fi
done
#判断用户输入的日期与当前日期前后
if [[ $CUR_DATE -lt $USER_DATE ]];then
ARISE $CUR_DATE $USER_DATE
echo "today is $CUR_DATE ,and little than $USER_DATE $num days"
elif [[ $CUR_DATE -gt $USER_DATE ]];then
DRISE $CUR_DATE $USER_DATE
echo "today is $CUR_DATE ,and bigger than $USER_DATE cha $num days"
else
echo "oh,it's today $(date +'%F')"
fi