Search code examples
shelldateprintfksh

ksh93 date calculation using builtin printf function


I need to do date calculations in a shell script. Unfortunately my operating system (SunOS) does not provide a very handy date function: it does not support the -d option which is exactly what I need.

Roaming on the web to find an alternate solution i found something that looks to be powerful enough with ksh93 printf builtin function. It supports syntaxes like that:

yesterday=${ printf "%(%Y%m%d)T" yesterday; }
friday=${ printf "%(%Y%m%d)T" "3 days ago"; }

In my case, i need to calculate 2 days before a calculated date, in my understanding it should be written like that (mydate is formatted as "YYYYMMDD"):

dayinthepast=${ printf "%(%Y%m%d)T" "3 days before $mydate"; }

or

dayinthepast=${ printf "%(%Y%m%d)T" "$mydate - 3 days"; }

But it does not work.

The more surprising is that the second syntax is recognized but it takes the minus as a plus and add 3 days to the given date.

I have read a useful blog covering the ksh93 printf builtin syntax but it does not cover my case. I'm giving the link here (thanks for the author): ksh93-date-manipulation

Any help would be appreciated. Thanks


Solution

  • this worked for me on AIX 7.1:

    $ ksh93
    $ MY_DATE=20210601
    $ printf "%(%Y%m%d)T" "${MY_DATE} 3 days ago"
    20210529
    

    got the hint from the link - ksh93-date-manipulation - there's a paragraph there that mentions "23 days ago"