bashdategnu

how to find date of nth occurrence of a particular day of the week (e.g. Sunday) in a particular month in gnu date bash


I want to find the date for the third Sunday of the month for a given month using the gnu date command in bash.

I know that one can write this to find the next Sunday from now:

 date +%Y%m%d -d "next sunday" 

(and could then add n weeks), but after reading the man page I don't see how to do this relative to a particular date, e.g. like

 date +%Y%m%d -d "20221001+next sunday" 

or actually

 date +%Y%m%d -d "20221001+next sunday+2 weeks" 

I've found this specific question answered for a lot of other languages on SO, or this similar question for gnu date in bash, but not this specific question using gnu date.


Solution

  • You could calculate it starting with the weekday %w of the first day in that month:

    n=3        # The third
    w=0        # Sunday (0=Sun .. 6=Sat)
    ym=202411  # in November 24
    d=$(((n-1)*7+(w-$(date +%w -d $ym'01')+7)%7+1))
    
    echo $d    # gives 17