Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: print the next monday of date

Tags:

bash

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`
like image 649
Vincenzo Avatar asked Oct 15 '25 04:10

Vincenzo


1 Answers

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
like image 92
chepner Avatar answered Oct 19 '25 09:10

chepner