计算时间差(evaluate time difference in days)
时间:2008-07-08 来源:kim_wei
在一些应用中经常需要得到两个时间的差值。
比如, 在图书管理上,可以根据还书时间和当前时间的差值来判断是否向借书人发送Email作为提醒。
下面的脚本片断可以完成这种功能. (运行环境:OpenSuSE Linux 10.3, bash) #!/bin/bash #total seconds of day 60x60x24 day_seconds=86400 year=""
mon="" day="" cur="" year1="" mon1="" day1="" tar=""
sec=0 day_diff=0
#################################
## ##get time difference (in days) ## get_date_diff() {
#get current day, month, year
day=`date +%d`
mon=`date +%m`
year=`date +%Y` #change current time to seconds
#counted from 1970-01-01 01:00:00
cur=`date -d $year"-"$mon"-"$day +%s` #you have to give target date (year, mon1, day1)
#for example, by using arguments of script
tar=`date -d $year1"-"$mon1"-"$day1 +%s` #calculate the difference
#firstly, get difference of seconds
sec=`expr $tar - $cur`
day_diff=`expr $sec / $day_seconds` echo "Difference of Days: "$day_diff
} ################################# ## script start from here
year1=$1 mon1=$2 day1=$3
get_date_diff
比如, 在图书管理上,可以根据还书时间和当前时间的差值来判断是否向借书人发送Email作为提醒。
下面的脚本片断可以完成这种功能. (运行环境:OpenSuSE Linux 10.3, bash) #!/bin/bash #total seconds of day 60x60x24 day_seconds=86400 year=""
mon="" day="" cur="" year1="" mon1="" day1="" tar=""
sec=0 day_diff=0
#################################
## ##get time difference (in days) ## get_date_diff() {
#get current day, month, year
day=`date +%d`
mon=`date +%m`
year=`date +%Y` #change current time to seconds
#counted from 1970-01-01 01:00:00
cur=`date -d $year"-"$mon"-"$day +%s` #you have to give target date (year, mon1, day1)
#for example, by using arguments of script
tar=`date -d $year1"-"$mon1"-"$day1 +%s` #calculate the difference
#firstly, get difference of seconds
sec=`expr $tar - $cur`
day_diff=`expr $sec / $day_seconds` echo "Difference of Days: "$day_diff
} ################################# ## script start from here
year1=$1 mon1=$2 day1=$3
get_date_diff
相关阅读 更多 +