查找bash的两个日期之间的区别 [英] Find difference between two dates in bash

查看:109
本文介绍了查找bash的两个日期之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到两个日期之间的区别:

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)

不过,这将返回

date: invalid date ‘82800’

这是为什么,我怎么能得到期望的结果?

Why is this, and how can I get the desired result?

推荐答案

您可以使用:

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'

和输出是:

23:00:00

但是,超过24小时的任意差异,你不得不开始担心如何为生命的价值将被重新presented。负值也将present问题。

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.

这样做的问题是,如果你把格式字符串,日期presented是:

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.

考虑加入引用%j 为一年的日子。它会工作半三立长达1年的区别。

Consider adding %j for the day of year; it will work semi-sanely for up to 1 year's difference.

另外,捕获一个变量present的差异与单独计算的结果。

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

输出:

+0 23:00:00

(含义:0天23小时0分0秒积极的变化)拆分的天数,如1000年进入,月,天是没有任何参考日期误人子弟。在这里,有参考日期帮助,但它仍然是...有趣。

(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.

这篇关于查找bash的两个日期之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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