在 CentOS(或其他 Linux 系统)里,“时间戳比对”通常有几种常见场景,下面按最常用的方式给你说明。
date +%s
输出示例:
1719300000
这是 Unix 时间戳(秒)。
如果是毫秒:
date +%s%3N
date -d "2024-06-25 12:00:00" +%s
date -d @1719300000
或指定格式:
date -d @1719300000 "+%Y-%m-%d %H:%M:%S"
时间戳本质是整数,可以直接比大小。
t1=$(date -d "2024-06-25 10:00:00" +%s)
t2=$(date -d "2024-06-25 12:00:00" +%s)
if [ "$t1" -lt "$t2" ]; then
echo "t1 早于 t2"
fi
testif [ file1 -nt file2 ]; then
echo "file1 比 file2 新"
fi
-nt:newer than-ot:older thanstat -c %Y file1
如果日志是这种格式:
2024-06-25 12:00:00
转成时间戳再比:
ts1=$(date -d "2024-06-25 12:00:00" +%s)
ts2=$(date -d "2024-06-25 11:00:00" +%s)
[ "$ts1" -gt "$ts2" ] && echo "时间更晚"
diff=$(( $(date +%s) - $(date -d "2024-06-24 12:00:00" +%s) ))
echo "相差 $diff 秒"
如果你能说一下具体场景(比如:比对日志、比对文件、写脚本、crontab、还是程序里),我可以给你更针对性的示例。