mbcharney
mbcharney

Reputation: 355

Calculate third monday of month

I have searched and searched but can't seem to find anything that will fit what i am trying to do, and I can't seem to figure out how to make it work.

Here's the over view: My computer club meets on the third Monday of every month, with the club board meeting one week later. On our club website they are manually changing this date every month... :(

I am trying to automate it using PHP. I have had a little luck, but for the most part it won't come out right.

Here is the code example I am using:

//Set Default Time Zone
date_default_timezone_set('America/New_York');

//Define Variables Needed
$now = date("U");
$currmonth = date("n");
$curryear = date("Y");
$monthyear = date("F Y");
$thirdmon = date('U', strtotime($monthyear.' third monday'));
$thirdtue = date('U', strtotime($monthyear.' third tuesday'));

//Check for current date before or after third monday of the current meeting month
if ($now > $thirdtue) {
    $monthyear = date("F Y", strtotime('next month'));
    $thirdmon = date('U', strtotime($monthyear.' third monday'));
}

echo date("l F d, Y", $thirdmon);

I added the the $thirdtue variable because checking against the $thirdmon variable was causing a problem on the actual meeting date with it jumping to the next months meeting date, so I check against the third Tues and it doesn't jump until midnight on the meeting date now.

Now the weird thing is that I was working on this on March 30, 2014 and it was showing April 21, 2014 as the next meeting date which is correct. When the time rolled to midnight, 00:00 and the date changed to March 31, 2014 the meeting date changed to May 19, 2014!?!?!

I am also having problems with a couple of other parts of the code that do some other calculations, but I figure if i can get this down then I should be able to work out the rest.

Can anyone tell me where I coming off the rails with this??

Upvotes: 2

Views: 5595

Answers (2)

Shane
Shane

Reputation: 1230

$third_monday = new DateTime('third monday of this month');

// if date has passed, get next month's third monday
if ($third_monday < new DateTime()) {
    $third_monday->modify('third monday of next month');
}

echo $third_monday->format('l F d, Y');

Upvotes: 5

austin-schick
austin-schick

Reputation: 1245

I don't have very much experience with php but I threw this together. It's been tested, and it seems to work.

<?php
   date_default_timezone_set('America/New_York');

   $currmonth = date("n");
   $curryear = date("Y");
   $currthirdmon =  date("d", strtotime("third monday", mktime(0,0,0,$currmonth,1,$curryear)));

   if ($currthirdmon < date("d"))
   {
    $nextmeeting = date("l F d, Y", strtotime("third monday", mktime(0,0,0,$currmonth+1,1,$curryear)));
   }
   else
   {
     $nextmeeting = date("l F d, Y", strtotime("third monday", mktime(0,0,0,$currmonth,1,$curryear)));
   }

   print $nextmeeting;
?>

Upvotes: 1

Related Questions