linux計算時間差

來源:互聯網
上載者:User

linux計算時間差 為了計算留存,需要知道多個從時間差,來擷取不同的時間點。 以下代碼在輸入值與當前值,在同一月份時,不會有問題。但是如果是誇月份回溯資料,那麼就會出現較大的問題。 #Date variables forif [ -n "$1" ]; then    TODAY=`date -d "" +"%Y%m%d"`    base=$(($TODAY-$1))elif [ -z "${DAYAGO1}" ]; then    base=0fiarr=($base $(($base+1)) $(($base+2)) $(($base+8)) $(($base+31)))dag=(0 1 2 8 31) for i in {0..4}; do    echo $i    echo ${dag[$i]}    echo ${arr[$i]}    export "DAYAGO${dag[$i]}"=`date -d "${arr[$i]} days ago" +"%Y%m%d"`done 為了修正bug,可以參考英文文章: http://stackoverflow.com/questions/3385003/shell-script-to-get-difference-in-two-datesThere's a solution that almost works: use the %s date format of GNU date, which prints the number of seconds since 1970-01-01 00:00. These can be subtracted to find the time difference between two dates. echo $(( ($(date -d 2010-06-01 +%s) - $(date -d 2010-05-15 +%s)) / 86400))But the following displays 0 in some locations: echo $((($(date -d 2010-03-29 +%s) - $(date -d 2010-03-28 +%s)) / 86400))Because of daylight savings time, there are only 23 hours between those times. You need to add at least one hour (and at most 23) to be safe. echo $((($(date -d 2010-03-29 +%s) - $(date -d 2010-03-28 +%s) + 43200) / 86400))Or you can tell date to work in a timezone without DST. echo $((($(date -u -d 2010-03-29 +%s) - $(date -u -d 2010-03-28 +%s)) / 86400))(POSIX says to call the reference timezone is UTC, but it also says not to count leap seconds, so the number of seconds in a day is always exactly 86400 in a GMT+xx timezone.) 最終結果就接近完美了,為: #Date variables forif [ -n "$1" ]; then    TODAY=`date -d "" +"%Y%m%d"`    BACKDAY=$1    base=$((($(date -d $TODAY +%s) - $(date -d $BACKDAY +%s) + 43200) / 86400))elif [ -z "${DAYAGO1}" ]; then    base=1fiarr=($(($base)) $(($base+1)) $(($base+7)) $(($base+30)))dag=(1 2 8 31) for i in {0..3}; do    echo ${dag[$i]}    echo ${arr[$i]}    export "DAYAGO${dag[$i]}"=`date -d "${arr[$i]} days ago" +"%Y%m%d"`done shell 中的時間計算轉為秒做相減運算 NOW=`date +"%Y-%m-%d %H:%M:%S"`LASTLINE=$(ls -lt * "$v_DIRNAME"| line | awk '{print $6,$7,$8}')    #擷取檔案的最後時間 2009-10-04 14:30:00 Sys_data=`date -d  "$CURTIME" +%s`    #把目前時間轉化為Linux時間In_data=`date -d  "$LASTLINE" +%s`interval=`expr $Sys_data - $In_data`  #計算2個時間的差 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.