I have a calendar starting on Monday.
May, 2011
----------------------------
Mon Tue Wed Thu Fri Sat Sun
----------------------------
25 26 27 28 29 30 1 week 1
2 3 4 5 6 7 8 week 2
9 10 11 12 13 14 15 week 3
16 17 18 19 20 21 22 week 4
23 24 25 26 27 28 29 week 5
30 31 1 2 3 4 5 week 6
I want to find week of month on giving Date.
Below works fine on the calendar that starts on Sunday.
function getWeekOfMonth(date) {
prefixes = ['1', '2', '3', '4', '5'];
return prefixes[0 | date.getDate() / 7];
}
But in my Calendar (Monday based) if I choose May 1st, the return value if "1" thus
gives me "week2" but it should be "week1".
If I choose May 15th, giving me "week4" instead of "week3".
It works on things like May 12th.
I tried to shift this one day gap (monday and sunday) and modified the algorithm which failed.
Could anyone show me how can I fix my algorithm correctly?
function getWeekOfMonth(date) {
prefixes = ['1', '2', '3', '4', '5'];
return prefixes[0 | date.getDate() - 1 / 7];
}
you first need to check on what day the month starts then add k so that date.getDate() + k is 7 for the first monday of the month
then it's pretty easy
function getWeekOfMonth(date) {
var adjustedDate = date.getDate()+k;
prefixes = ['0', '1', '2', '3', '4', '5'];
return prefixes[0 | adjustedDate / 7];
}
edit:
you can use getDay to find the current day of week and use it in relation to getDate to find the monday of the current week
function getWeekOfMonth(date) {
var day = date.getDate()
day-=(date.getDay()==0?6:date.getDay()-1);//get monday of this week
//special case handling for 0 (sunday)
day+=7;
//for the first non full week the value was negative
prefixes = ['0', '1', '2', '3', '4', '5'];
return prefixes[0 | (day) / 7];
}
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