shell计算日期之间的天数

来源:互联网 发布:标点符号检查软件 编辑:程序博客网 时间:2024/04/30 13:34

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" 1fidate1=$(date +%s -d "$1")if [ $? -ne 0 ]then    ret_err "first input date is illegal" 2fidate2=$(date +%s -d "$2")if [ $? -ne 0 ]then    ret_err "second input date is illegal" 2fiecho "$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" 2fi####### 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“ 3fiecho "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}




0 0