Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Week of the month

Tags:

date

shell

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?

like image 297
Vijay Bynagari Avatar asked Sep 24 '11 22:09

Vijay Bynagari


1 Answers

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.

like image 50
raphinesse Avatar answered Sep 18 '22 05:09

raphinesse