Saturday, April 25, 2015

Week of the Month

In my project work, I needed to find out whether the given date falls in 1st, 2nd, 3rd, 4th or 5th week of the given month. As usual, I googled for this solution and found many functions. http://www.hotscripts.com/forums/php/37900-week-number-month.html, http://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month and http://mybroadband.co.za/vb/showthread.php/66311-Calculating-the-week-in-the-month-(PHP) are some of them. But, being lazy, I thought those functions were too complex, and there could be a simpler solution to this. So I spent some time and came up with this function. Here is the code.
<?php
/**
* Copyright (C) 2016 Prabhas Gupte
*
* This is free script: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should also see <http://www.gnu.org/licenses/gpl.txt>
*/
function week_of_month($date) {
$timestamp = strtotime($date);
$year = date('Y', $timestamp);
$month = date('m', $timestamp);
$w1 = date('W', $timestamp); // current week of year
$w2 = date('W', strtotime('first thursday of this month')); // week of year, as on first Thursday of given month
return floor($w1-$w2+1);
}
week_of_month('2013-06-10');
?>

No comments:

Post a Comment