bashdateawk

How to get the date of the 3rd Wednesday in the month


I need a code sample getting the date of the 3rd Wednesday of the month. I simply can't wrap my head around how to do that - the last Wednesday is simple:

cal | awk '/^ *[0-9]/ { d=$4 } END { print d }'

Ultimately I need the script to return the "next 3rd wednesday" - as in, if we have passed the 3rd Wednesday of this month, then return the 3rd Wednesday of the following month.


Solution

  • Here's a simple approach which would work properly in most regions:

    #!/bin/bash
    
    export LC_TIME=C
    thismonth=$(date +%m)       # this month like "10"
    thisyear=$(date +%Y)        # this year like "2018"
    firstdayofweek=$(date -d "${thisyear}-${thismonth}-1" +%w)
    # calculates the day of week of the 1st day of the month
    # returns the number between 0 and 6, where 0=Sun, 1=Mon, ...
    
    wed1=$(( (10 - $firstdayofweek) % 7 + 1 ))
    # calculates the day of month of the 1st Wednesday
    wed3=$(( $wed1 + 14 ))
    # the day of the 3rd Wednsday
    
    echo $wed3
    

    which yields "17" as of today.
    It would be easy to modify the code above to achieve your next goal.