PHP Get monday, sunday, last monday & last sunday

A function I’ve put togheter for a work-related project to get date of monday, sunday, last monday & last sunday.. Might add in next monday and sunday later.


/**
* Get Mondays and Sundays
*
* Get monday, sunday, last monday & last sunday
* Example usage:
* // to retreive the dates using today as starting point
* $mondaysAndSundays = getMondaysAndSundays();
* // to retreive the dates using a custom date as starting point
* $mondaysAndSundays = getMondaysAndSundays('1987-04-14');
*
* @param date $offset Provide a date from where to calculate from in strtotime() translatable format. If none is given, today's date will be used.
*
* @return array
*
*/
function getMondaysAndSundays($offset=false)
{

if(!$offset) $offset = strtotime(date('Y-m-d'));
else $offset = strtotime($offset);

// this week
if(date('w',$offset) == 1)
{
$mas['monday'] = date('Y-m-d',$offset);
}
else
{
$mas['monday'] = date('Y-m-d',strtotime("last Monday",$offset));
}

if(date('w',$offset) == 6)
{
$mas['sunday'] = date('Y-m-d',$offset);
}
else
{
$mas['sunday'] = date('Y-m-d',strtotime("next Sunday",$offset));
}

// last week
if(date('w',$offset) == 1)
{
$mas['lastmonday'] =  date('Y-m-d',strtotime('-1 week',$offset));
}
else
{
$mas['lastmonday'] = date('Y-m-d',strtotime('-1 week', strtotime(date('Y-m-d',strtotime("last Monday",$offset)))));
}

if(date('w') == 6)
{
$mas['lastsunday'] = date('Y-m-d',strtotime('-1 week',$offset));
}
else
{
$mas['lastsunday'] = date('Y-m-d',strtotime("last Sunday",$offset));
}

return $mas;
}

You might also want to look at these posts

  • why vTiger sucks
  • What?! You Didn’t Google Him?
  • hostgator upgrades all their servers to PHP & MySQL 5
  • always_populate_raw_post_data disabled? here’s a workaround
  • memcache_connect() [function.memcache-connect]: Can’t connect to localhost:11211
  • 

    5 Responses (Add Your Comment)

    1. this works!
      thanks for the great post

    2. hi,
      i need to displays all sundays between two dates
      Ex:
      Start Date :12-8-2010
      End Date : 17-9-2010

      Please help me!………..
      Thanks in advance

    3. echo date(“Y-m-d”, strtotime($date.” last sunday”));

    4. // If you know the time, find out the beginning day and the end day of the week, in which the time is known:

      $start_date_w=time();

      while((date(“N”,$start_date_w))!=1) {
      $start_date_w=$start_date_w-(60*60*24); // define monday
      }
      $end_date_w=$start_date_w+(60*60*24*6); // define sunday

    5. Thanks for this, you gave me idea how to solve my problem :)

    Leave a Reply

    Formatting: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    Archives

    Twitter!