如何在bash下获得两个日期之间的差异

时间:2023-01-17 21:30:41

Exactly as the question sounds. I want to subtract say 20120115 from 20120203 and get 19 as the answer. What is the best way to implement this in a shell script?

就像这个问题听起来的一样。我想把20120203减去20115,得到19。在shell脚本中实现这一点的最佳方式是什么?

2 个解决方案

#1


25  

let DIFF=(`date +%s -d 20120203`-`date +%s -d 20120115`)/86400
echo $DIFF

#2


0  

A quick and utterly dirty fix that can be used in scripts (quick and also fast):

一个可以在脚本中使用的快速而彻底的修复(快速且快速):

function getdate { for dd in $(seq -w $1 $2) ; do date -d $dd +%Y%m%d 2>/dev/null ; done  ; }                                                                             

I use this function for other purposes related to log files. And to count the days:

我将此函数用于与日志文件相关的其他目的。数着日子:

echo "$(getdate YYYYmmdd YYYYmmdd)" | wc -l

YYYYmmdd have to be dates, of course. It only works if $1 is an earlier date than $2 and it's slow for large date differences, but for a period of a few years and to be used in ad-hoc scripting it's quite handy.

当然,YYYYmmdd必须是日期。它只适用于$1比$2更早的日期,并且它对于较大的日期差异是缓慢的,但是在几年的时间内,并且在特别的脚本中使用它是非常方便的。

And if you happen to have MySQl or similar installed there is a very quick option :

如果你碰巧有MySQl或类似的安装,有一个非常快的选择:

mysql -BNe "SELECT DATEDIFF($1,$2) AS DiffDate ;" | tr -d -

The last tr allows you to enter the dates in any order (MySQL would else render a '-'if the first date is earlier than the second)

最后一个tr允许您以任何顺序输入日期(如果第一个日期比第二个日期早,MySQL将呈现一个'-')

#1


25  

let DIFF=(`date +%s -d 20120203`-`date +%s -d 20120115`)/86400
echo $DIFF

#2


0  

A quick and utterly dirty fix that can be used in scripts (quick and also fast):

一个可以在脚本中使用的快速而彻底的修复(快速且快速):

function getdate { for dd in $(seq -w $1 $2) ; do date -d $dd +%Y%m%d 2>/dev/null ; done  ; }                                                                             

I use this function for other purposes related to log files. And to count the days:

我将此函数用于与日志文件相关的其他目的。数着日子:

echo "$(getdate YYYYmmdd YYYYmmdd)" | wc -l

YYYYmmdd have to be dates, of course. It only works if $1 is an earlier date than $2 and it's slow for large date differences, but for a period of a few years and to be used in ad-hoc scripting it's quite handy.

当然,YYYYmmdd必须是日期。它只适用于$1比$2更早的日期,并且它对于较大的日期差异是缓慢的,但是在几年的时间内,并且在特别的脚本中使用它是非常方便的。

And if you happen to have MySQl or similar installed there is a very quick option :

如果你碰巧有MySQl或类似的安装,有一个非常快的选择:

mysql -BNe "SELECT DATEDIFF($1,$2) AS DiffDate ;" | tr -d -

The last tr allows you to enter the dates in any order (MySQL would else render a '-'if the first date is earlier than the second)

最后一个tr允许您以任何顺序输入日期(如果第一个日期比第二个日期早,MySQL将呈现一个'-')