Skip to content

Instantly share code, notes, and snippets.

@gjergjsheldija
Created October 3, 2011 15:15
Show Gist options
  • Save gjergjsheldija/1259345 to your computer and use it in GitHub Desktop.
Save gjergjsheldija/1259345 to your computer and use it in GitHub Desktop.
find first and last day of month
<?php
function firstDayOfMonth() {
return date("d", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}
function lastDayOfMonth() {
return date("d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}
function getWeekofMonth( $startMonth, $endMonth ) {
$startDay = 0;
$endDay = 0;
// find monday and friday of the current week starting from today
switch ( $dayofWeek ) {
case 1 :
$startDay = $dayofMonth;
$endDay = $dayofMonth + 5;
break;
case 2 :
$startDay = $dayofMonth - 1;
$endDay = $dayofMonth + 3;
break;
case 3:
$startDay = $dayofMonth - 2;
$endDay = $dayofMonth + 2;
break;
case 4:
$startDay = $dayofMonth - 3;
$endDay = $dayofMonth + 1;
break;
case 5:
$startDay = $dayofMonth - 4;
$endDay = $dayofMonth;
break;
case 6:
$startDay = $dayofMonth + 2;
$endDay = $dayofMonth + 6;
break;
case 7:
$startDay = $dayofMonth + 3;
$endDay = $dayofMonth + 7;
break;
}
// if we are on the first / last day on the month..fix it
if( $startDay < firstDayOfMonth() )
$startDay = firstDayOfMonth();
if( $endDay > lastDayOfMonth() )
$endDay = lastDayOfMonth();
// check if the first / last day of the month is not saturday / sunday
$tmpStartDate = mktime(0,0,0, date("m"), $startDay, date("Y") );
$tmpEndDate = mktime(0,0,0, date("m"), $endDay, date("Y") );
// start saturday / sunday
if( date("N", $tmpStartDate) == 6 )
$startDay = $startDay - 1;
if( date("N", $tmpStartDate) == 7 )
$startDay = $startDay - 2;
// end saturday / sunday
if( date("N", $tmpEndDate) == 6 )
$endDay = $endDay - 1;
if( date("N", $tmpStartDate) == 7 )
$endDay = $endDay - 2;
// printing
echo "monday : " . date( "Y-m-d" , mktime(0,0,0, date("m"), $startDay, date("Y") ) ) . "\n";
echo "friday : " . date( "Y-m-d" , mktime(0,0,0, date("m"), $endDay, date("Y") ) ) . "\n";
}
echo getWeekofMonth('2011-05-01 ', '2011-05-31');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment