Finding date range for current week, month and year

The following code will give you the start and last date of a week:

   $today = getdate();
   print_r($today);
   echo "<br/>";

   $weekStartDate = $today['mday'] - $today['wday'];
   $weekEndDate = $today['mday'] - $today['wday']+6;
   echo "<br/>";
   echo "<br/>";
   echo "week start date:".$weekStartDate;
   echo "<br/>";
   echo "week end date:".$weekEndDate;

Hope it helps...


This solution is simple, and it takes in consideration when the current day is Monday or Sunday.

NOTE: Using strtotime('last monday') may work if the day is other than Monday, otherwise it will return the previous Monday. Because of that we should use strtotime('last monday', strtotime('tomorrow')) and it will work for any day of the current week =)

Solution:

$monday = strtotime('last monday', strtotime('tomorrow'));
$sunday = strtotime('+6 days', $monday);
echo "<P>". date('d-M-Y', $monday) . " to " . date('d-M-Y', $sunday) . "</P>";

 function rangeMonth ($datestr) {
   date_default_timezone_set (date_default_timezone_get());
   $dt = strtotime ($datestr);
   return array (
     "start" => date ('Y-m-d', strtotime ('first day of this month', $dt)),
     "end" => date ('Y-m-d', strtotime ('last day of this month', $dt))
   );
 }

 function rangeWeek ($datestr) {
   date_default_timezone_set (date_default_timezone_get());
   $dt = strtotime ($datestr);
   return array (
     "start" => date ('N', $dt) == 1 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('last monday', $dt)),
     "end" => date('N', $dt) == 7 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('next sunday', $dt))
   );
 }

 print_r (rangeMonth('2011-4-5')); // format: YYYY-M-D
 print_r (rangeWeek('2011-4-5'));

output for rangeMonth()

Array
(
    [start] => 2011-04-01
    [end] => 2011-04-30
)

output for rangeWeek()

Array
(
    [start] => 2011-04-04
    [end] => 2011-04-08
)

Notice: functions like getdate(), date(), etc. throw Warning if default time zone is not set in php.ini.


you can use strtotime

example :

    date('d.m.Y',strtotime('last day of this month')) 
date('d.m.Y',strtotime('last monday'))  // for first day of this week

Tags:

Php