Linux 如何比较两个 DateTime 字符串并以小时为单位返回差异?(bash 外壳)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8116503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 07:11:35  来源:igfitidea点击:

How to compare two DateTime strings and return difference in hours? (bash shell)

linuxshellunix

提问by denormalizer

I can do that in php with the following code:

我可以使用以下代码在 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);

$hDiffwill give me the result in hours.

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

How do I implement the above in bash shell?

如何在 bash shell 中实现上述内容?

采纳答案by another.anon.coward

You could use datecommand to achieve this. man datewill provide you with more details. A bash script could be something on these lines (seems to work fine on Ubuntu 10.04 bash 4.1.5):

您可以使用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"

Hope this helps!

希望这可以帮助!