Calculate the first Friday of next month with PHP

UPDATE: This script has been updated, see: http://www.web-geek.net/posts/2009/02/14/first-friday-script-updated-and-simplified/

While developing phx2600.org, I ran into a slight dilemma.  The PHX2600 meetings occur once a month on the first Friday of every month, and we wanted to display that on the site.  However, it was becoming a tedious chore to change the date once a month manually.  So, being the automation addict I am, I thought, why not write a script.  So one night I hammered out the following script that will calculate the first Friday of next month:

<?php
 
  /***************************************
  *  FILENAME: first-friday.php          *
  *  AUTHOR:   Chris Kankiewicz [PHLAK]  *
  *  WEBSITE:  http://www.web-geek.net   *
  ***************************************/
 
  // START FUNCTIONS
 
  function get_day($describer,$weekday,$reference_date) { // $reference_date format = m-Y
 
    $d = explode('-',$reference_date);
 
    switch ($describer) {
      case 'first': $offset = get_day_offset($reference_date,$weekday); break;
    }
 
    $r = mktime(0,0,0,$d[0],1+$offset,$d[1]);
    return $r;  //returns timestamp format
  }
 
  function get_day_offset($anchor,$target) { //$anchor format = m-Y
 
    $ts = explode('-',$anchor);
    $ts = mktime(0,0,0,$ts[0],'01',$ts[1]);
 
    $anchor = date("w",$ts);
    $target = strtolower($target);
    $days = array(
      'sunday'=>0,
      'monday'=>1,
      'tuesday'=>2,
      'wednesday'=>3,
      'thursday'=>4,
      'friday'=>5,
      'saturday'=>6
    );
 
    $offset = $days[$target] - $anchor;
 
    if ($offset<0) $offset+=7;
 
    return $offset;  //returns 0-6 for use in get_day();
  }
 
  //END FUNCTIONS
 
  $t = getdate(); //Get today's date
 
  $today = date('m-Y',$t[0]); //Display today's date as MM-YYYY
 
  //Calculate Next Month
  if($t[mon] == '12'){
    $nm = '1-'.($t[year]+1);
  } elseif($t[mday] <= '7' && $t[wday] <= '5') {
    $nm = ($t[mon]).'-'.$t[year];
  }	else {
    $nm = ($t[mon]+1).'-'.$t[year];
  }
 
  $date = get_day("first", "friday", $nm);
 
  //Checks if today is after the first friday of the month
  if($t[mon] == date('m',$date)
    && $t[mday] > date('j',$date)
    && $t[mon] == '12') {
      $nm = '1-'.($t[year]+1);
      $ff = get_day("first", "friday", $nm);
  } elseif($t[mon] == date('m',$date)
    && $t[mday] > date('j',$date) && $t[mon] != '12') {
      $nm = ($t[mon]+1).'-'.$t[year];
      $ff = get_day("first","friday",$nm);
  }	else {
    $ff = $date;
  }
 
  // I know this code is crap, deal with it or fix it yourself!
 
  echo date("F j, Y", $ff);
 
?>

I apologies for the crappy code, I was either tired, drunk or both the night I wrote this.

This entry was posted in Programming, Scripting, Web Development and tagged , , , . Bookmark the permalink.

4 Responses to Calculate the first Friday of next month with PHP

  1. tintub says:
    <?php
     
    $nextMonth = (date('n') + 1) % 12;
    $year = $nextMonth == 1 ? date('Y') + 1 : date('Y');
    $firstDayOfNextMonth = date('N', mktime(0, 0, 0, $nextMonth, 1, $year));
    $firstFriday = 6 - $firstDayOfNextMonth;
    if ($firstFriday &lt;= 0) $firstFriday += 7;
    echo "First Friday falls on day $firstFriday\n";
     
    ?>

    (This code is untested for anything except current date btw)

  2. tintub says:

    I forgot to account for December (mod 12 = 0)

    <?php
     
    $nextMonth = (date('n') + 2) % 12;
    if ($nextMonth == 0) $nextMonth += 12;
    $year = $nextMonth == 1 ? date('Y') + 1 : date('Y');
    $firstDayOfNextMonth = date('N', mktime(0, 0, 0, $nextMonth, 1, $year));
    echo "First day of $nextMonth $year is $firstDayOfNextMonth\n";
    $firstFriday = 6 - $firstDayOfNextMonth;
    if ($firstFriday <= 0) $firstFriday += 7;
    echo "First Friday falls on day $firstFriday\n";
     
    ?>
  3. d3r1v3d says:

    Just for the hell of it, I wrote a script which does the same thing (I believe). Not sure how this is going be formatted once I post this, so I apologize in advance if it looks shitty:

    <?php
    $date_today = getdate();
     
    $timestamp_firstOfMonth =
        mktime($date_today['hours'], $date_today['minutes'], $date_today['seconds'],
               $date_today['mon'], 1, $date_today['year']);
     
    $date_firstOfMonth = getdate($timestamp_firstOfMonth);
     
    $date_firstFriday = array();
    if ($date_firstOfMonth['wday'] != 5)
    {
        $dateOffset = 0;
        if ($date_firstOfMonth['wday'] &lt; 5)
        {
            $dateOffset = 5 - $date_firstOfMonth['wday'];
        }
        else
        {
            $dateOffset = 6;
        }
     
        $date_firstFriday = getdate(
            mktime($date_firstOfMonth['hours'], $date_firstOfMonth['minutes'], $date_firstOfMonth['seconds'],
                   $date_firstOfMonth['mon'], ($date_firstOfMonth['mday'] + $dateOffset), $date_today['year'])
        );
    }
    else
    {
        $date_firstFriday = $date_firstOfMonth;
    }
     
    echo 'This month, the meeting will take place on: '
         . $date_firstFriday['year'] . '/' . $date_firstFriday['mon'] . '/' . $date_firstFriday['mday'];
    ?>
  4. Pingback: First Friday script updated and simplified | Web Geek

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">