How to find the difference in days between two dat

2019-01-03 09:54发布

A="2002-20-10"
B="2003-22-11"

How to find the difference in days between two dates?

标签: bash shell date
17条回答
家丑人穷心不美
2楼-- · 2019-01-03 10:04

Another Python version:

python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"
查看更多
别忘想泡老子
3楼-- · 2019-01-03 10:08

I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:

A=2003-12-11
B=2002-10-10
DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
echo $DIFF
查看更多
SAY GOODBYE
4楼-- · 2019-01-03 10:09

Even if you don't have GNU date, you'll probably have Perl installed:

use Time::Local;
sub to_epoch {
  my ($t) = @_; 
  my ($y, $d, $m) = ($t =~ /(\d{4})-(\d{2})-(\d{2})/);
  return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
}
sub diff_days {
  my ($t1, $t2) = @_; 
  return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
}
print diff_days("2002-20-10", "2003-22-11"), "\n";

This returns 398.041666666667 -- 398 days and one hour due to daylight savings.


The question came back up on my feed. Here's a more concise method using a Perl bundled module

days=$(perl -MDateTime -le '
    sub parse_date { 
        @f = split /-/, shift;
        return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]); 
    }
    print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
' $A $B)
echo $days   # => 398
查看更多
【Aperson】
5楼-- · 2019-01-03 10:12

Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.

date1=2012-09-22
date2=2013-01-31
. date-funcs-sh
_date2julian "$date1"
jd1=$_DATE2JULIAN
_date2julian "$date2"
echo $(( _DATE2JULIAN - jd1 ))

See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml

查看更多
Root(大扎)
6楼-- · 2019-01-03 10:14

If you have GNU date, it allows to print the representation of an arbitrary date (-d option). In this case convert the dates to seconds since EPOCH, subtract and divide by 24*3600.

Or you need a portable way?

查看更多
男人必须洒脱
7楼-- · 2019-01-03 10:14

Assume we rsync Oracle DB backups to a tertiary disk manually. Then we want to delete old backups on that disk. So here is a small bash script:

#!/bin/sh

for backup_dir in {'/backup/cmsprd/local/backupset','/backup/cmsprd/local/autobackup','/backup/cfprd/backupset','/backup/cfprd/autobackup'}
do

    for f in `find $backup_dir -type d -regex '.*_.*_.*' -printf "%f\n"`
    do

        f2=`echo $f | sed -e 's/_//g'`
        days=$(((`date "+%s"` - `date -d "${f2}" "+%s"`)/86400))

        if [ $days -gt 30 ]; then
            rm -rf $backup_dir/$f
        fi

    done

done

Modify the dirs and retention period ("30 days") to suit your needs.

查看更多
登录 后发表回答