I am trying to get the week number of the month and this is what I am trying to do:
x=`date +"%V"`
echo "x is $x"
y=`date +"%V" -d $(date +"%Y%m01")`
echo "y is $y"
week_of_month=$((x-y))
echo "week_of_month is $week_of_month"
and this is what I get:
x is 38
y is 38
week_of_month is 0
But if my statment is working correctly the value of y should be 35 or so. What am I doing wrong?
This worked for me on OS X:
week_today=$(date "+%W")
week_start_of_month=$(date -v1d "+%W")
week_of_month=$[week_today - week_start_of_month + 1]
This assumes Monday to be the first day of the week. If you want Sunday to be treated as the first day of the week instead you'd have to substitute %W
with %U
.
This gives a week number from 1 to 6. If you'd like to have a zero indexed week number instead just drop the + 1
in the last line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With