开发者

Week of the month

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
开发者_StackOverflow中文版

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.


echo $((($(date +%-d)-1)/7+1))


You cannot trust date +%V because it gives the (apparently useless) ISO week of year.

This means you get odd-ball results, like Jan.1 being the 52nd week of the year.

E.g.:

date --date='2012-01-01 12pm UTC' +%V
52


This seems to be the most portable solution:

#/bin/sh

_DOM=`date +%d`
_WOM=$(((${_DOM}-1)/7+1))


On Mac OS X, I was able to do this for the desired result.

y=`date -v1d +%V`


on Solaris 5.10

date +%V works fine.

refer to man pages of Date for your machine.


Im not a shell person, But if you want to find the week number an algorithm like this will do.

Find the offset , the date of the first sunday, for march 2012 it is 4. (yourdate+offset)/7 will give you the week of month that it is.

you can easily do this in c# , dont know about shell.


For Linux, try below command

Week=$(($(date "+%W")-$(date --date="$(date --date="$(($DAY-1)) days ago")" +"%V")+1))

This will calculate the current week number and subtract the week number of start date of the month. Remove +1 at the end if you want to start the week number of the month from '0'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜