I have an array of random dates (not coming from MySQL). I need to group them by the week as Week1, Week2, and so on upto Week5.
What I have is this:
The corect way is
function weekOfMonth($date) {
$firstOfMonth = date("Y-m-01", strtotime($date));
return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
}
//It's easy, no need to use php function
//Let's say your date is 2017-07-02
$Date = explode("-","2017-07-02");
$DateNo = $Date[2];
$WeekNo = $DateNo / 7; // devide it with 7
if(is_float($WeekNo) == true)
{
$WeekNo = ceil($WeekNo); //So answer will be 1
}
//If value is not float then ,you got your answer directly
Given the time_t wday (0=Sunday through 6=Saturday) of the first of the month in firstWday
, this returns the (Sunday-based) week number within the month:
weekOfMonth = floor((dayOfMonth + firstWday - 1)/7) + 1
Translated into PHP:
function weekOfMonth($dateString) {
list($year, $month, $mday) = explode("-", $dateString);
$firstWday = date("w",strtotime("$year-$month-1"));
return floor(($mday + $firstWday - 1)/7) + 1;
}
I have created this function on my own, which seems to work correctly. In case somebody else have a better way of doing this, please share.. Here is what I have done.
function weekOfMonth($qDate) {
$dt = strtotime($qDate);
$day = date('j',$dt);
$month = date('m',$dt);
$year = date('Y',$dt);
$totalDays = date('t',$dt);
$weekCnt = 1;
$retWeek = 0;
for($i=1;$i<=$totalDays;$i++) {
$curDay = date("N", mktime(0,0,0,$month,$i,$year));
if($curDay==7) {
if($i==$day) {
$retWeek = $weekCnt+1;
}
$weekCnt++;
} else {
if($i==$day) {
$retWeek = $weekCnt;
}
}
}
return $retWeek;
}
echo weekOfMonth('2015-09-08') // gives me 2;
You can use the function below, fully commented:
/**
* Returns the number of week in a month for the specified date.
*
* @param string $date
* @return int
*/
function weekOfMonth($date) {
// estract date parts
list($y, $m, $d) = explode('-', date('Y-m-d', strtotime($date)));
// current week, min 1
$w = 1;
// for each day since the start of the month
for ($i = 1; $i <= $d; ++$i) {
// if that day was a sunday and is not the first day of month
if ($i > 1 && date('w', strtotime("$y-$m-$i")) == 0) {
// increment current week
++$w;
}
}
// now return
return $w;
}
function getWeekOfMonth(DateTime $date) {
$firstDayOfMonth = new DateTime($date->format('Y-m-1'));
return ceil(($firstDayOfMonth->format('N') + $date->format('j') - 1) / 7);
}
Goendg solution does not work for 2016-10-31.