2012-07-06 59 views
1

好的,我現在的情況是我想知道在2013年5月15日之前的特定日期,究竟有多少天。剩下的日期並不重要,計算出達到那一天之前的剩餘天數。找出剩餘時間在Linux中的時間

我覺得做這樣的(僞代碼):

y=$end_year-$cur_year 

if [ y -ge 1 ]; then 
    days=$y*365 
else 
    continue 
fi 

if [ $end_month -gt $cur_month ]; then 
    m=$end_month-$cur_month 
else 
    contine 
fi 

if [ $end_day -gt $cur_day ]; then 
    d=$end_day-$cur_day 
else 
    continue 
fi 

result=$days+$m+$d 

現在我不知道是否有這樣做的更簡單的方法,因爲我很新的Linux和shell腳本,所以如果有一個更好的方法來做到這一點,請幫助我。

回答

5

這一個從UNIX時間戳的差來計算它:

date 
Fri Jul 6 15:04:04 BST 2012 
echo $(((`date -d "May 15, 2013" +'%s'` - `date +'%s'`)/(60*60*24))) 
312 

司地板,所以你必須添加1,如果分數天計爲一整天。

1
[06 Jul 2012 18:13:47] [email protected] ~ 
$ DIFF=$(($(date -d '05/15/2013 00:00' +%s) - $(date +%s))) ; \ 
    echo $((DIFF/(3600*24))) days $((DIFF % (3600*24)/3600)) \ 
    hours $((DIFF % 3600/60)) minutes $((DIFF % 60)) seconds left 
312 days 5 hours 46 minutes 13 seconds left