如何比较两个DateTime字符串和返回小时的差异?(bash shell)



我可以在php中使用以下代码:

$dt1 = '2011-11-11 11:11:11';
$t1 = strtotime($dt1);
$dt2 = date('Y-m-d H:00:00');
$t2 = strtotime($dt2);
$tDiff = $t2 - $t1;
$hDiff = round($tDiff/3600);

$hDiff将在几小时内给我结果。

如何在bash shell中实现上述功能?

您可以使用date命令来实现这一点。man date将为您提供详细信息。bash脚本可以是这些行(似乎在Ubuntu 10.04 bash 4.1.5上工作得很好):

#!/bin/bash                                                                                                                                                   
# Date 1
dt1="2011-11-11 11:11:11"
# Compute the seconds since epoch for date 1
t1=$(date --date="$dt1" +%s)
# Date 2 : Current date
dt2=$(date +%Y-%m-%d %H:%M:%S)
# Compute the seconds since epoch for date 2
t2=$(date --date="$dt2" +%s)
# Compute the difference in dates in seconds
let "tDiff=$t2-$t1"
# Compute the approximate hour difference
let "hDiff=$tDiff/3600"
echo "Approx hour diff b/w $dt1 & $dt2 = $hDiff"

希望这对你有帮助!

最新更新