RSS - Latest posts Week of the Month in Mysql

Home » 2009 » 04 » Week of the Month in Mysql
SELECT WEEK(my_date_field,5) -
WEEK(DATE_SUB(my_date_field, INTERVAL DAYOFMONTH(my_date_field)-1 DAY),5)+1


Recently I needed to get the number of the week in a certain month. There is the handy WEEK() function, however it only gives you the week of the year.

Obviously before we can go through the code above, a definition of the nth week of the month is needed (as I realized after asking the question on stackoverflow…):

For me the week starts on a Monday, and the first week of the month does not have to be a full week – if a month starts on a Friday, the Friday to Sunday days count as the first week.

With this out of the way here is a quick explanation of what goes on above.

WEEK(my_date_field,5)

First we get the actual week number of the year for the specified date. The second parameter is there to define Monday as the first day of the week (more details in Mysql manual).

DAYOFMONTH(my_date_field)

Next we get the day of the month for the specified date.

DATE_SUB(my_date_field, DAYOFMONTH(my_date_field)-1 DAY)

We can use that number with DATE_SUB to get the date for the 1st day of the month. This in turn can be used to get the week number for the 1st week of the month.

SELECT WEEK(my_date_field,5) -
WEEK(DATE_SUB(my_date_field, INTERVAL DAYOFMONTH(my_date_field)-1 DAY),5)+1

Finally we subtract the first day’s week from the actual week number which should give us the month’s week number starting from 0. Thus the final +1 if you want the count to start from 1.

 

You can leave a response, or trackback from your own site.

Add Comment

  1. Tee says:

    Just wanted to give you a big thanks for this code! It’s such a simple idea but more complicated to achieve than it should be, but you nailed it.

  2. amar12312 says:

    I think, this is wrong answer.
    For eg. just take January 2010 month and apply above formula. After applying formula we have got only first 3 dates in 1st week. But in our definition, as this is week of month, it should consist first seven dates in 1st week of month.

    to calculate week of month in MySql there is simple calculation involved.

    CEILING(DAYOFMONTH(date_column)/7)

  3. Joanna says:

    Your formula only calculates increments of 7 days. The first 3 days being in week 1 is the expected behaviour… 4th is a Monday and thus week 2 for Jan 2010.

  4. steve says:

    can i have the formula for the week starting from thursday

  5. livelybrowsers says:

    Thanks for good stuff

  6. roclafamilia says:

    Helpful blog, bookmarked the website with hopes to read more!