如何比较两个 DateTime 字符串并以小时为单位返回差异?(bash 外壳) [英] How to compare two DateTime strings and return difference in hours? (bash shell)

查看:30
本文介绍了如何比较两个 DateTime 字符串并以小时为单位返回差异?(bash 外壳)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 php 中使用以下代码做到这一点:

I can do that in php with the following code:

$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 会在几小时内给我结果.

$hDiff will give me the result in hours.

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

How do I implement the above in bash shell?

推荐答案

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

You could use date command to achieve this. man date will 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):

#!/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"

希望这有帮助!

这篇关于如何比较两个 DateTime 字符串并以小时为单位返回差异?(bash 外壳)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆