1
\$\begingroup\$

I need to determine a meeting date which convenes on the second Thursday of every month.

I've written the following code to do this:

//Determine next monthly meeting (occurs on 2nd thursday of each month)
define('MAX_POSSIBLE_SECOND_THURS', 14);
define('JANUARY', 1);
define('DECEMBER', 12);
define('THURSDAY', 4);

$current_month  =   intval(date('n'));
$next_month     =   $current_month == DECEMBER ? 1 : $current_month + 1;
$current_day    =   intval(date('j'));

$iThursdayCount =   0;
$month_to_use   =   $current_day <= MAX_POSSIBLE_SECOND_THURS ? $current_month : $next_month;
$year_to_use    =   $month_to_use <> JANUARY ? intval(date('Y')) : intval(date('Y')) + 1;
for ($iDay = 1; $iDay <= MAX_POSSIBLE_SECOND_THURS; $iDay++) {
        $date_to_check  =   strtotime($year_to_use.'-'.$month_to_use.'-'.$iDay);
        if(date('N', $date_to_check)== THURSDAY) {
        $iThursdayCount++;
        if ($iThursdayCount == 2)
           break;
    }
}

$next_meeting_date = $month_to_use.'/'.$iDay.'/'.$year_to_use;

echo $next_meeting_date;

Although the loop is small, it seems like a lot of work to determine the second Thursday. Are there any improvements that can be made? Or would you do something totally different?

\$\endgroup\$
6
\$\begingroup\$

Try the DateTime class. With this you can use relative formats:

new DateTime('second thu of next month');
new DateTime('second thu of jul');

That should make the code a lot easier.

\$\endgroup\$
  • \$\begingroup\$ I turned 20 lines of code to 3 with no loops. Beautiful! ty. \$\endgroup\$ – ray023 Jan 31 '12 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.