shell计算日期之间的天数

2015-08-05 成都

1. 利用date将日期转化为秒数$(date +%s -d "$date")

2.计算日期之间的差值,除以一天的秒数,得到相差的天数

-------------------caldays.sh
#!/bin/sh

. ./error.sh

######
# DESC:     caculate the days between two specific date
# NOTE:     2015-07-03     created by Jack Liu
######

######
# check the input arugments
# 1. need two arguments
# 2. check if the date formate legal
# 3. the end date should be greater than the begin date
######
if [ $# != 2 ]
then
    ret_err "usage: $(basename $0) beg_date end_date" 1
fi

date1=$(date +%s -d "$1")
if [ $? -ne 0 ]
then
    ret_err "first input date is illegal" 2
fi

date2=$(date +%s -d "$2")
if [ $? -ne 0 ]
then
    ret_err "second input date is illegal" 2
fi

echo "$1 convert to $date1"
echo "$2 convert to $date2"

if [ $date2 -lt $date1 ]
then
    ret_err "end date should be greater than the begin date" 2
fi

######
# caculate the distance between the two date
# 1. caculate the difference between two date
# 2. because the unit of date2 and date1 is second,
#     the difference should be divided by 60 * 60 * 24
######
diffr=`expr $date2 - $date1`
convalue=`expr 60 \* 60 \* 24`
if [ $convalue -ne 0 ]
then
    diffr=`expr $diffr / $convalue`
else
    ret_err "divided by 0“ 3
fi

echo "the difference between the two date is $diffr"
exit 0


--------------------error.sh
######
# operation:     print the error message and exit
# precondition:  need two arguments, the error message and the return value
# postcondition: print the error message and exit
######
function ret_err()
{
    echo "error: $1"
    exit $2
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值