bash 在bash中查找两个日期之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20831765/
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
Find difference between two dates in bash
提问by gandalf3
I attempted to get the difference between two dates with:
我试图通过以下方式获得两个日期之间的差异:
date -d $(echo $(date -d "Sun Dec 29 02:22:19 2013" +%s) - $(date -d "Sun Dec 28 03:22:19 2013" +%s) | bc)
However, this returns
然而,这返回
date: invalid date ‘82800'
Why is this, and how can I get the desired result?
为什么会这样,我怎样才能得到想要的结果?
回答by Jonathan Leffler
You can use:
您可以使用:
date1="Sat Dec 28 03:22:19 2013"
date2="Sun Dec 29 02:22:19 2013"
date -d @$(( $(date -d "$date2" +%s) - $(date -d "$date1" +%s) )) -u +'%H:%M:%S'
And the output is:
输出是:
23:00:00
However, for arbitrary differences over 24 hours, you have to start worrying about how the value for days will be represented. Negative values will also present problems.
但是,对于超过 24 小时的任意差异,您必须开始担心天的值将如何表示。负值也会出现问题。
The problem with this is that if you drop the format string, the date presented is:
问题在于,如果删除格式字符串,则显示的日期为:
Thu Jan 1 23:00:00 UTC 1970
So, while this works for the two given date/time values, it is not really a general solution.
因此,虽然这适用于两个给定的日期/时间值,但它并不是真正的通用解决方案。
Consider adding %jfor the day of year; it will work semi-sanely for up to 1 year's difference.
考虑添加%j一年中的某一天;它将半健全地工作长达 1 年的差异。
Otherwise, capture the difference in a variable and present the results with a separate calculation.
否则,捕获变量中的差异并通过单独的计算呈现结果。
date1="Sat Dec 28 03:22:19 2013"
date2="Sun Dec 29 02:22:19 2013"
delta=$(( $(date -d "$date2" +%s) - $(date -d "$date1" +%s) ))
if [[ $delta -lt 0 ]]
then sign="-"; delta=${delta/^-/}
else sign="+"
fi
ss=$(( $delta % 60 ))
delta=$(( $delta / 60 ))
mm=$(( $delta % 60 ))
delta=$(( delta / 60 ))
hh=$(( $delta % 24 ))
dd=$(( $delta / 24 ))
printf "$sign%d %.2d:%.2d:%.2d\n" $dd $hh $mm $ss
Output:
输出:
+0 23:00:00
(Meaning: a positive difference of 0 days, 23 hours, 0 minutes, 0 seconds.) Splitting a number of days such as 1000 into years, months and days is fraught without any reference dates. Here, there are reference dates to help, but it would still be ... fun.
(意思是:0 天、23 小时、0 分钟、0 秒的正差。)将诸如 1000 天之类的天数拆分为年、月和日,这充满了没有任何参考日期的情况。在这里,有参考日期可以提供帮助,但它仍然会......很有趣。

