Search code examples
bashdatesolarissubtractionsunos

How subtract days from date in bash shell on Solaris 11?


I've been trying subtrac some days $days from a date $date with format yyyy-MM-dd, but nothing has worked on Solaris 11. Some solution is a 'trick' with the timezone, but it depends on the timezone and I think that is exactly that, a trick.

I would like a cheaper solution, because the only thing I can think is to convert the date to julian representation and then subtract one day and again obtain yyyy-MM-dd representation, for example:

date=2000-12-31
days=1
julian=$(toJulian $date)
resultJulian=$(subtractDays $julian $days)
resultGregorian=toGregorian $resultJulian

So, how can I do it without all this proccess? Thanks.


Solution

  • If you don't have GNU date or GNU awk, consider perl:

    subtractDays() {
      local date numDays
      date=$1
      numDays=$2
    
      date=$date days=$numDays perl -e '
        use Env qw(date days);
        use Time::Piece;
        use Time::Seconds;
    
        my $start_time = Time::Piece->strptime($date, "%Y-%m-%d");
        my $end_time = $start_time - (ONE_DAY * $days);
        print $end_time->ymd . "\n";'
    }
    

    ...thereafter:

    subtractDays 2000-12-31 1
    

    ...emits...

    2000-12-30