Home > Net >  Get date with same day in month
Get date with same day in month

Time:09-17

I want to get all dates with the same day of week.

inputDate="2021/08/25"

That means I should get all the same day of week as inputDate.

outputDates="2021/08/04,2021/08/11,2021/08/18,2021/08/25"

I only got this so far..

 inputDate="2021/08/25"
 dd=$(date -d "$inputDate"  "%Y/%m/%d")

So what I'm planning is to do "date -7" and loop 5 times forward and backward and collect it then check if value of month is still the same with inputDate if not then drop it

Do you have any way to do this?

CodePudding user response:

Using only shell, the easyest way to get all weekdays from a month is by using cal command:

cal -n1 8 2021

outputs:

     August 2021    
Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7 
 8  9 10 11 12 13 14 
15 16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31             
                 

Then you can filter using sed, awk or other tools to reach your goal.

Example:

year=2021
month=8
day=25

weekday_number="$(date -d$year-$month-$day  %w)"
cn=$(($weekday_number   1))

cal -n1 $month $year |
    sed -r 's/(..)\s/\1\t/g;s/  //g' |
    awk -v cn=$cn -F'\t' 'NR<3 || $cn == "" {next} {print $cn}' |
    while read wday; do
        echo $year/$month/$wday
    done

outputs:

2021/8/4
2021/8/11
2021/8/18
2021/8/25

CodePudding user response:

Without using cal or ncal...

#!/bin/bash

inputDate="2021/08/25"

dow=$(date -d "$inputDate"  "%a")
month=$(date -d "$inputDate"  "%m")
outputDates=""

for x in $(seq 0 9)
do
    validDate=$(date -d "$x $dow 5 week ago"  "%Y/%m/%d" | grep "/$month/")
    if [ ! -z $validDate ]
    then
        if [ ! -z $outputDates ]
        then
            outputDates="$outputDates,$validDate"
        else
            outputDates="$validDate"
        fi
    fi
done

echo "$outputDates"

This script outputs:

2021/08/04,2021/08/11,2021/08/18,2021/08/25
  • Related