Skip to main content

date

Shell 範例
# Sample
today=$(date +%Y/%m/%d)
NOW=`date "+%Y/%m/%d %H:%M:%S"`

eval `date "+day=%d; month=%m; year=%Y"`
BKNAME="cacti-backup-$year-$month-$day.tar.gz"

# Sample
# %T time; same as %H:%M:%S
NOWD=$(date +"%F")   # YYYY-MM-DD
NOWT=$(date +"%T")  # H:M:S

#
eggs="202/07/29"
days="20 days"
echo "Eggs expiry date $(date -d "${eggs}+${days}")"
將 Date 轉換為 EPOCH 時間格式
## Date to Epoch
# 用 perl 可用於 AIX
perl -e 'use Time::Local; print timelocal(0,25,1,11,11,2008), "\n";'

# On Linux
# Current date
date +%s
# For specified date
date --date="2023/11/1" +%s

For AIX

Time2Epoch() {
    local dtime yyyy mm dd HH MM SS
    dtime="$1"
    yyyy=$(echo "$dtime" | cut -d ' ' -f1 | cut -d '/' -f1)
    mm=$(echo "$dtime" | cut -d ' ' -f1 | cut -d '/' -f2)
    dd=$(echo "$dtime" | cut -d ' ' -f1 | cut -d '/' -f3)
    HH=$(echo "$dtime" | cut -d ' ' -f2 | cut -d ':' -f1)
    MM=$(echo "$dtime" | cut -d ' ' -f2 | cut -d ':' -f2)
    SS=$(echo "$dtime" | cut -d ' ' -f2 | cut -d ':' -f3)

    echo $(perl -e 'use Time::Local; ($yyyy, $mm, $dd, $HH, $MM, $SS)=@ARGV; $tm=timelocal($SS, $MM, $HH, $dd, $mm - 1, $yyyy); print "$tm";' $yyyy $mm $dd $HH $MM $SS)
    return 
}

Epoch2Date() {
    local epochtime datetime
    epochtime=$1
    datetime=
    if [ -n "$epochtime" ]
    then
        datetime=$(perl -le 'print scalar localtime $ARGV[0]' ${epochtime})
    fi
    echo $datetime
}

常用日期格式
date +"%D %T"
02/04/21 01:42:52

date "+%y-%m-%d_%H%M%S"
17-05-22_105503

date "+%Y/%m/%d"
2015/07/17

date "+%F"
2015-07-17

# Display past date
date --date="49 days ago"
日  9月 11 16:17:02 CST 2016

date --date="1 month ago"
五  9月 30 16:17:34 CST 2016

# Display future date
date --date="next fri"
五  2月  5 00:00:00 CST 2021

date --date='TZ="America/New_York" 10:00 next fri'
五  2月  5 23:00:00 CST 2021
計算程式執行所花費的時間
start=`date "+%Y/%m/%d %H:%M:%S"`
start_s=$(date -d "$start" +%s)

Sleep 20

end=`date "+%Y/%m/%d %H:%M:%S"`
end_s=$(date -d "$end" +%s)
diff=$((end_s - start_s))