Get the First or Last Friday in a Month

The language-agnostic version:

To get the first particular day of the month, start with the first day of the month: yyyy-mm-01. Use whatever function is available to give a number corresponding to the day of the week. Subtract that number from the day you are looking for; for example, if the first day of the month is Wednesday (2) and you're looking for Friday (4), subtract 2 from 4, leaving 2. If the answer is negative, add 7. Finally add that to the first of the month; for my example, the first Friday would be the 3rd.

To get the last Friday of the month, find the first Friday of the next month and subtract 7 days.


Perhaps it can be made quicker...
This was VERY interesting to code.

Please note that $direction is 1 for forward and -1 for backward to ease things up :)
Also, $day begins with a value of 1 for Monday and ends at 7 for Sunday.

function get_date($month, $year, $week, $day, $direction) {
  if($direction > 0)
    $startday = 1;
  else
    $startday = date('t', mktime(0, 0, 0, $month, 1, $year));

  $start = mktime(0, 0, 0, $month, $startday, $year);
  $weekday = date('N', $start);

  if($direction * $day >= $direction * $weekday)
    $offset = -$direction * 7;
  else
    $offset = 0;

  $offset += $direction * ($week * 7) + ($day - $weekday);
  return mktime(0, 0, 0, $month, $startday + $offset, $year);
}

I've tested it with a few examples and seems to work always, be sure to double-check it though ;)


PHP's built-in time functions make this simple.

http://php.net/manual/en/function.strtotime.php

// Get first Friday of next month.
$timestamp = strtotime('first fri of next month');

// Get second to last Friday of the current month.
$timestamp = strtotime('last fri of this month -7 days');

// Format a timestamp as a human-meaningful string.
$formattedDate = date('F j, Y', strtotime('first wed of last month'));

Note that we always want to make sure that we've defined the correct timezone for use with strtotime so that PHP has an understanding of where to compute the timestamp for relative to what time zone the machine thinks it's in.

date_default_timezone_set('America/New_York');
$formattedDate = date('F j, Y', strtotime('first wed of last month +1 week'));

Tags:

Datetime

Php