Date arithmetic formating in Bash

Solution 1:

You can use date to do the arithmetic for you. With BSD date:

$ /bin/date +%V
03
$ /bin/date -v-1w +%V
02

From man date:

-v   Adjust (i.e., take the current date and display the result of the
     adjustment; not actually set the date) the second, minute, hour,
     month day, week day, month or year according to val.  If val is
     preceded with a plus or minus sign, the date is adjusted forwards
     or backwards according to the remaining string, otherwise the
     relevant part of the date is set.  The date can be adjusted as
     many times as required using these flags.  Flags are processed in
     the order given.

In case you have installed and are using GNU date:

$ date -d '-1week' +%V
02
$ date -d '-1 week' +%V
02
$ date -d 'now - 1 week' +%V
02
$ date -d 'last week' +%V
02

Solution 2:

A "one-liner" (OK, two-liner) is

WEEKNBR=$(date +"%V")
PREVWK=$(printf %02d $((WEEKNBR-1)))

Solution 3:

I think what you are after here is a way to check if $PREVWK is 2 digits long or not, in which case you respectively either prepend a 0 to the beginning of the existing number or not.

Implementation:

WEEKNBR=$(date +"%V")
PREVWK=$((WEEKNBR-1))

if [[ $(echo -n ${PREVWK} | wc -c) -lt 2 ]] ; then
    PREVWK="0${PREVWK}"
fi

It looks at the number of digits in the variable (be sure it is always a number) and decides if it is made up of less than 2 digits. If so, it prepends 0, else it leaves the number alone. This way, weeks like 23 will stay as 23 instead of 023, and so on.

Let me know if that works for you or if you are looking for another/different way to achieve it. You could also check if the number as a whole is less than 10, meaning a leading 0 needs to be added.

Solution 4:

A one liner approach that won't break when the new year rolls around and that always gives the correct week number for seven days before the current moment:

weeknbr="$(date +%V)"
prevwk="$(date -j -v -7d +%V)"

Note that I'm using lower case names because these are not (or should not be) environment variables; see:

  • Are there naming conventions for variables in shell scripts?

P.S.: I see that muru has written an essentially identical answer, but I had this tab open for some hours before getting back to it and neglected to refresh.