Reputation: 97
How can I calculate the date of the Monday of next week? For example, if I have one variable with this day:
DAYCHECK=2012-10-24
the calculation of the next-monday doesn't work:
date -d $DAYCHECK -dnext-monday +%Y%m%d
UPDATE:
I have solved whit this method:
numdaycheck=`date -d $DAYCHECK +%u`
sum=$((8-$numdaycheck))
date=`date -d "$DAYCHECK $sum days" +%Y%m%d`
Upvotes: 4
Views: 4533
Reputation: 19315
next_monday() {
local yi=${1:0:4} mi=${1:5:2} di=${1:8:2}
mi=${mi#0}
di=${di#0}
local yo=$yi mo=$mi do
do=$(cal -m $mi $yi|awk 'c==1{print$1;exit}NR>2&&/'"$di"'/{c++}')
if [ "X$do" = X ];then
((mo=mi+1))
if ((mo>12)); then
((mo=1,yo=yi+1))
fi
do=$(cal -m $mo $yo|awk 'NR>2&&!/^ /{print$1;exit}')
fi
printf "%04d-%02d-%02d\n" $yo $mo $do
}
Upvotes: 0
Reputation: 195049
(echo commands are not necessary.)
kent$ w=$(date -d2012-10-24 +%u) // here get the weekday index
kent$ echo $w
3
kent$ s=$(((7-$w+2)*3600*24+$(date -d2012-10-24 +%s))) //here get the "next monday" seconds
kent$ echo $s
1351548000
kent$ echo $(date +%Y-%m-%d -d "1970-01-01 UTC $s seconds") //finally we get the date of "next monday"
2012-10-29
so the "2012-10-29
" is the final answer.
This way is not as simple as chepner's . I post as another answer because I usually do date calculation with it. for example add 5 hours 30 mins to a given date. just change (7-$w+2)*3600*24
part will do.
Hope it helps someone some day.
Upvotes: 0
Reputation: 531075
If GNU date
(or any other date
) accepts some variation of "monday after $DAYCHECK", I haven't seen it. I think you have to do the math.
$ day_of_week=$( date +%u --date $DAYCHECK) # 1 = Monday, ... 7 = Sunday
$ date --date "$DAYCHECK +$((8-day_of_week)) days"
If DAYCHECK
is already a Monday, you'll get the following Monday. If you want DAYCHECK
instead, you'll need to handle it separately:
$ if (( day_of_week == 1 )); then
> date --date "$DAYCHECK"
> else
> date --date "$DAYCHECK +$((8-day_of_week)) days"
> fi
Upvotes: 5