Organizational Research By

Surprising Reserch Topic

php get number of week for month


php get number of week for month  using -'php,date'

So I have a script that returns the number of weeks in a particular month and year. How can I take a specific day from that month and determine if it is part of week 1,2,3,4 or 5 of that month?
    

asked Sep 24, 2015 by sameer rathore
0 votes
2 views



Related Hot Questions

22 Answers

0 votes

The most frustrating thing I have ever tried to get working - but here it is!


answered Sep 24, 2015 by loknath.ganji
0 votes

http://thecodecave.com/2011/06/01/find-what-week-of-the-month-a-date-is-in-php/ suggests $weekNum = date("W") - date("W", strtotime(date("Y-m-01", time()))) + 1;

For a specific day (instead of now):

$day = time(); // or whatever unix timestamp, etc
$weekNum = date('W', $day) - date('W', strtotime(date('Y-m-01', $day))) + 1;

Please note that $day = strtotime('Oct 31, 2011'); will return 6 (some rare months have 6 weeks in them).

answered Sep 24, 2015 by 20shahi
0 votes
public function getWeeks($timestamp)
{
    $maxday    = date("t",$timestamp);
    $thismonth = getdate($timestamp);
    $timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']);    //Create time stamp of the first day from the give date.
    $startday  = date('w',$timeStamp);    //get first day of the given month
    $day = $thismonth['mday'];
    $weeks = 0;
    $week_num = 0;

    for ($i=0; $i<($maxday+$startday); $i++) {
        if(($i % 7) == 0){
            $weeks++;
        }
        if($day == ($i - $startday + 1)){
            $week_num = $weeks;
        }
      }     
    return $week_num;
}

Hello all i have been struggling for the whole day trying to figure this code out, i finally figured it out so i thought i would share it with you all.

all you need to do is put a time stamp into the function and it will return the week number back to you.

thanks

answered Sep 24, 2015 by vijaygupta1980
0 votes

I realize I am a little late to the game, but thought I would throw out more of a mathematical solution...

function week_of_month($date) {
    $date_parts = explode('-', $date);
    $date_parts[2] = '01';
    $first_of_month = implode('-', $date_parts);
    $day_of_first = date('N', strtotime($first_of_month));
    $day_of_month = date('j', strtotime($date));
    return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}

and a test for it

foreach (range(1, 30) as $day) {
    $test_date = "2012-06-" . str_pad($day, 2, '0', STR_PAD_LEFT);
    echo "$test_date - ";
    echo week_of_month($test_date) . "\n";
}

Output

2012-06-01 - 1
2012-06-02 - 1
2012-06-03 - 2
2012-06-04 - 2
2012-06-05 - 2
2012-06-06 - 2
2012-06-07 - 2
2012-06-08 - 2
2012-06-09 - 2
2012-06-10 - 3
2012-06-11 - 3
2012-06-12 - 3
2012-06-13 - 3
2012-06-14 - 3
2012-06-15 - 3
2012-06-16 - 3
2012-06-17 - 4
2012-06-18 - 4
2012-06-19 - 4
2012-06-20 - 4
2012-06-21 - 4
2012-06-22 - 4
2012-06-23 - 4
2012-06-24 - 5
2012-06-25 - 5
2012-06-26 - 5
2012-06-27 - 5
2012-06-28 - 5
2012-06-29 - 5
2012-06-30 - 5

note
This always assumes new weeks start on Sunday. Though this would be pretty easy to account for any day of the week being considered the starting date by changing the 1 being subtracted in this line:

return floor(($day_of_first + $day_of_month - 1) / 7) + 1;

to the appropriate value for the day in question.

answered Sep 24, 2015 by dhananjayksharma
0 votes

there is a problem with this method. if the passing date (Lets say 2012/01/01 which is a Sunday) and "$rollover" day is "Sunday", then this function will return 2. where its actually is 1'st week. i think i have fixed it in following function. please add comments to make it better.

function getWeeks($date, $rollover)
{
    $cut        = substr($date, 0, 8);
    $daylen     = 86400;
    $timestamp  = strtotime($date);
    $first      = strtotime($cut . "01");   
    $elapsed    = (($timestamp - $first) / $daylen)+1;
    $i          = 1;
    $weeks      = 0;
    for($i==1; $i<=$elapsed; $i++)
    {
        $dayfind        = $cut . (strlen($i) < 2 ? '0' . $i : $i);
        $daytimestamp   = strtotime($dayfind);
        $day            = strtolower(date("l", $daytimestamp));
        if($day == strtolower($rollover))
        {
            $weeks++;  
        }
    } 
    if($weeks==0)
    {
        $weeks++; 
    }
    return $weeks;  
}
answered Sep 24, 2015 by tejas lakhani
0 votes

Just Copy and Past the code and pass month and year.

e.g month=04 year=2013.

That's exactly what You Need.

$mm= $_REQUEST['month'];
$yy= $_REQUEST['year'];
$startdate=date($yy."-".$mm."-01") ;
$current_date=date('Y-m-t');
$ld= cal_days_in_month(CAL_GREGORIAN, $mm, $yy);
$lastday=$yy.'-'.$mm.'-'.$ld;
$start_date = date('Y-m-d', strtotime($startdate));
$end_date = date('Y-m-d', strtotime($lastday));
$end_date1 = date('Y-m-d', strtotime($lastday." + 6 days"));
$count_week=0;
$week_array = array();

for($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date. ' + 7 days')))
{
    $getarray=getWeekDates($date, $start_date, $end_date);
echo "
"; $week_array[]=$getarray; echo "\n"; $count_week++; } // its give the number of week for the given month and year echo $count_week; //print_r($week_array); function getWeekDates($date, $start_date, $end_date) { $week = date('W', strtotime($date)); $year = date('Y', strtotime($date)); $from = date("Y-m-d", strtotime("{$year}-W{$week}+1")); if($from < $start_date) $from = $start_date; $to = date("Y-m-d", strtotime("{$year}-W{$week}-6")); if($to > $end_date) $to = $end_date; $array1 = array( "ssdate" => $from, "eedate" => $to, ); return $array1; // echo "Start Date-->".$from."End Date -->".$to; } for($i=0;$i<$count_week;$i++) { $start= $week_array[$i]['ssdate']; echo "--"; $week_array[$i]['eedate']; echo "
"; }

OUTPUT:

week( 0 )=>2013-03-01---2013-03-02

week( 1 )=>2013-03-03---2013-03-09

week( 2 )=>2013-03-10---2013-03-16

week( 3 )=>2013-03-17---2013-03-23

week( 4 )=>2013-03-24---2013-03-30

week( 5 )=>2013-03-31---2013-03-31
answered Sep 24, 2015 by pradip.bhoge
0 votes

This is a solution based on sberry's mathematical solution but using the PHP DateTime class instead.

function week_of_month($date) {
    $first_of_month = new DateObject($date->format('Y/m/1'));
    $day_of_first = $first_of_month->format('N');
    $day_of_month = $date->format('j');
    return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}
answered Sep 24, 2015 by nimisha.jagtap
0 votes

This is the snippet that I made to fulfill my requirements for the same. Hope this will help you.

function getWeek($timestamp) {
 $week_year = date('W',$timestamp);
 $week = 0;//date('d',$timestamp)/7;
 $year = date('Y',$timestamp);
 $month = date('m',$timestamp);
 $day = date('d',$timestamp);
 $prev_month = date('m',$timestamp) -1;
if($month != 1 ){
    $last_day_prev = $year."-".$prev_month."-1";
    $last_day_prev = date('t',strtotime($last_day_prev));
    $week_year_last_mon = date('W',strtotime($year."-".$prev_month."-".$last_day_prev));
    $week_year_first_this = date('W',strtotime($year."-".$month."-1"));
    if($week_year_first_this == $week_year_last_mon){
        $week_diff = 0;
    }
    else{
        $week_diff = 1;
    }
    if($week_year ==1 && $month == 12 ){
    // to handle December's last two days coming in first week of January
        $week_year = 53;
    }
    $week = $week_year-$week_year_last_mon + 1 +$week_diff;
}
else{
 // to handle first three days January coming in last week of December.
    $week_year_first_this = date('W',strtotime($year."-01-1"));
    if($week_year_first_this ==52 || $week_year_first_this ==53){
        if($week_year == 52 || $week_year == 53){
            $week =1;
        }
        else{
            $week = $week_year + 1;
        }
    }
    else{
        $week = $week_year;
    }
}
return $week;

}

answered Sep 24, 2015 by shegokar.anjeet
0 votes

This is probably not a good way to do this but it's my first thought and I'm really tired.

Put all your dates into an array. The date object must have a day name (Monday). Create a method that searches the array and when ever you hit a Sunday you add 1 to a week counter. Once you find the date you're looking for return the week counter. That is the week the day falls in of the year. For the week in the month you have to reset the week counter every time you get to the last day in each month.

answered Sep 24, 2015 by patelnikul321
0 votes

I found a easy way to determine what week of the month today is in, and it would be a small change to have it work on any other date. I'm adding my two cents in here as I think my way is much more compact then the methods listed.

$monthstart = date("N",strtotime(date("n/1/Y")));
$date =( date("j")+$monthstart ) /7;
$ddate= floor( $date );
if($ddate != date) {$ddate++;}

and $ddate contains the week number you could modify it like so

function findweek($indate)
{
  $monthstart = date("N",strtotime(date("n/1/Y",strtotime($indate))));
  $date =( date("j",strtotime($indate))+$monthstart ) /7;
  $ddate= floor( $date );
  if($ddate != date) {$ddate++;}
  return $ddate;
}

and it would return what week of the month any date you give it is. what it does is first find the number of days from the start of the week to the first of the month. then adds that on to the current date then divides the new date by 7 and that will give you how many weeks have passed since the start of the month, including a decimal place for the part of the the current week that has passed. so what I do next is round down that number, then compare the rounded down version to the original if the two match your at the end of the week so it's already in the number. if they don't then just add one to the rounded down number and voila you have the current week number.

answered Sep 24, 2015 by yogeshplv
0 votes

For a Monday-Sunday (ISO 8601) week (or, if you simply don't care), you can do this in one line:

function get_week_of_month($date) {
 return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}

(adapted from http://mybroadband.co.za/vb/showthread.php/66311-Calculating-the-week-in-the-month-(PHP)?s=75bffb48a96d677a9088cc32f15d2992&p=946001&viewfull=1#post946001)

For anything else, (e.g. a Sunday-Saturday week), you just need to tweak $date inside the function:

function get_week_of_month($date) {
 $date += 86400; //For weeks starting on Sunday
 return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}

(Thanks to http://forums.whirlpool.net.au/archive/704023)

NOTE: You may run into some issues at the end of the year (e.g. around 12/31, 1/1, etc.) Read more here: http://forums.whirlpool.net.au/archive/704023

answered Sep 24, 2015 by gauravg.gwl
0 votes

Thought I'd share my function as well. This returns an array of weeks. Every week is an array with weeks day (0..6) as key and months day (1..31) as value.

Function assumes that week starts with Sunday.

Enjoy!

function get_weeks($year, $month){

    $days_in_month = date("t", mktime(0, 0, 0, $month, 1, $year));
    $weeks_in_month = 1;
    $weeks = array();

    //loop through month
    for ($day=1; $day<=$days_in_month; $day++) {

        $week_day = date("w", mktime(0, 0, 0, $month, $day, $year));//0..6 starting sunday

        $weeks[$weeks_in_month][$week_day] = $day;

        if ($week_day == 6) {
            $weeks_in_month++;
        }

    }

    return $weeks;

}
answered Sep 24, 2015 by deepak
0 votes

My 5 cents:

/**
* calculate number of weeks in a particular month
*/
function weeksInMonth($month=null,$year=null){

    if( null==($year) ) {
        $year =  date("Y",time());  
    }

    if(null==($month)) {
        $month = date("m",time());
    }

    // find number of days in this month
    $daysInMonths =  date('t',strtotime($year.'-'.$month.'-01'));

    $numOfweeks = ($daysInMonths%7==0?0:1) + intval($daysInMonths/7);

    $monthEndingDay= date('N',strtotime($year.'-'.$month.'-'.$daysInMonths));

    $monthStartDay = date('N',strtotime($year.'-'.$month.'-01'));

    if($monthEndingDay<$monthStartDay){

        $numOfweeks++;

    }

    return $numOfweeks;
}
answered Sep 24, 2015 by rajeevr642
0 votes

I create this function, from brazil :) I hope it is useful

function weekofmonth($time) {

    $firstday       = 1;
    $lastday        = date('j',$time);
    $lastdayweek = 6; //Saturday

    $week = 1;
    for ($day=1;$day<=$lastday;$day++) {
        $timetmp = mktime(0, 0, 0, date('n',$time), $day, date('Y',$time));
        if (date('N',$timetmp) == $lastdayweek) {
            $week++;
        }
    }
    if (date('N',$time)==$lastdayweek) {
        $week--;
    }

    return $week;
}

$time = mktime(0, 0, 0, 9, 30, 2014);
echo weekofmonth($time);
answered Sep 24, 2015 by yogeshplv
0 votes

Srahul07's solution works perfectly... If you abide by the Monday-Sunday week system! Here in 'murica, non-business folk tend to go by Sunday-Saturday being a week, so May 1, 2011 is week 1 and May 2, 2011 is still week 1.

Adding the following logic to the bottom of his function, right before it returns $week will convert this to a Sunday -> Monday system:

if (!date('w',strtotime("$year-$month-01")) && date('w',$timestamp))
    $week--;
elseif (date('w',strtotime("$year-$month-01")) && !date('w',$timestamp))
    $week++;

That seems to work for all cases, months starting with Sundays, January of 2011, 2012, and 2013, and all sorts of other random dates I plugged in. Thanks for that function, S. Rahul.

Sadly, after all my work to get that function up and running, I learn that my users use a more ridiculous system wherein the concept of "weeks" is too complicated, so they simply number the occurrences of a day in the month and ignore whatever "week" we're in. A brute-force system of counting how many Fridays, etc. have already occurred in the month is the only solution I could come up with, because that's all their logic is. T_T

answered Sep 24, 2015 by sameer rathore
0 votes

After alot of efoort i found the solution

 Start date=$startdate End date=$enddate 
"; } return $output; } if(isset($_POST) && !empty($_POST)){ $month = $_POST['m']; $year = $_POST['y']; echo getWeeks($month,$year); } ?> M: Y:
answered Sep 24, 2015 by sandeep bhadauria
0 votes

I really liked @michaelc's answer. However, I got stuck on a few points. It seemed that every time Sunday rolled around, there was an offset of one. I think it has to do with what day of the week is the start of the week. In any case, here is my slight alteration to it, expanded a bit for readability:

function wom(\DateTime $date) {
    // The week of the year of the current month
    $cw = date('W', $date->getTimestamp());

    // The week of the year of the first of the given month
    $fw = date('W',strtotime(date('Y-m-01',$date->getTimeStamp())));

    // Offset
    $o = 1;

    // If it is a Saturday, offset by two.
    if( date('N',$date->getTimestamp()) == 7 ) {
        $o = 2;
    }

    return $cw -$fw + $o;
}

So if the date is Nov. 9, 2013...

$cw = 45
$fw = 44

and with the offset of 1, it correctly returns 2.

If the date is Nov. 10, 2013, $cw and $fw are the same as before, but the offset is 2, and it correctly returns 3.

answered Sep 24, 2015 by okesh.badhiye
0 votes
function get_week_of_month( $timestamp )
{
    $week_of_month = 0; 
    $month = date( 'j', $timestamp );
    $test_month = $month;
    while( $test_month == $month )
    {
        $week_of_month++;
        $timestamp = strtotime( '-1 week', $timestamp );
        $test_month = date( 'j', $timestamp );
    }
    return $week_of_month;
}
answered Sep 24, 2015 by ajit.chavhan
0 votes

I found this online: http://kcwebprogrammers.blogspot.de/2009/03/current-week-in-month-php.html

He has a very simple solution which seems to work fine for me.

$currentWeek = ceiling((date("d") - date("w") - 1) / 7) + 1;

So for example:

$now = strtotime("today");
$weekOfMonth = ceil((date("d", $now) - date("w", $now) - 1) / 7) + 1;
answered Sep 24, 2015 by jekbishnoi
0 votes

you can use W in newer php versions. http://php.net/manual/en/function.date.php

i have used it like so:

function getWeek($date) { 
$month_start=strtotime("1 ".date('F Y',$date));
$current_date=strtotime(date('j F Y',$date));

$month_week=date("W",$month_start);
$current_week=date("W",$current_date);
return ($current_week-$month_week);

}//0 is the week of the first.
answered Sep 24, 2015 by gauravsinghal83

...