#!/bin/bash
# Our given dates
dates=(
20190315
20180217
20170914
)
# Loop over the given dates
for thedate in "${dates[@]}"; do
# Get day of the week as digit (1 is Monday, 7 is Sunday)
day=$( date -d "$thedate" +%u )
# The Monday the same week is $(( day - 1 )) days earlier than the given date.
# The Monday two weeks earlier is 14 days earlier still.
date -d "$thedate -$(( day - 1 + 14 )) days" +"$thedate --> %Y%m%d"
done
Output:
20190315 --> 20190225
20180217 --> 20180129
20170914 --> 20170828
The difficult bit about this is to figure out how to construct the correct --date
or -d
string for GNU date
to compute the final date. I opted for computing the day of week of the given date, and then using that to compute a date string that offsets the given date by a number of days so that the resulting date is the Monday two weeks earlier.
The actual strings that ends up being used for the option argument to -d
in the above script, using the dates given in the script, are
20190315 -18 days
20180217 -19 days
20170914 -17 days
Condensing the script into a single command that does the computation for a single date in $thedate
:
date -d "$thedate -$(date -d "$thedate" +%u) days -13 days" +%Y%m%d
or
date -d "$thedate -$(date -d "$thedate" +"-%u days -13 days")" +%Y%m%d
20190225
and20180129
and20170828
, am I correct ?