Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all fridays from current month

Tags:

php

I have a problem,

$fridays = array();
$fridays[0] = date('Y-m-d', strtotime('first friday of this month'));
$fridays[1] = date('Y-m-d', strtotime('second friday of this month'));
$fridays[2] = date('Y-m-d', strtotime('third friday of this month'));
$fridays[3] = date('Y-m-d', strtotime('fourth friday of this month'));
$fridays[4] = date('Y-m-d', strtotime('fifth friday of this month'));

but there is no fifth friday. Some months have fifth fridays. How to check and not set the last item array?

like image 361
user1642439 Avatar asked Jan 16 '23 12:01

user1642439


2 Answers

$fifth = strtotime('fifth friday of this month');

if (date('m') === date('m', $fifth)) {
  $fridays[4] = date('Y-m-d', $fifth);
}
like image 136
xdazz Avatar answered Jan 18 '23 02:01

xdazz


You can do this using the PHP date function. Get the month you want in $timestamp and then do something like this:

<?php
function fridays_get($month, $stop_if_today = true) {

$timestamp_now = time();

for($a = 1; $a < 32; $a++) {

    $day = strlen($a) == 1 ? "0".$a : $a;
    $timestamp = strtotime($month . "-$day");
    $day_code = date("w", $timestamp);
    if($timestamp > $timestamp_now)
        break;
    if($day_code == 5)
        @$fridays++;

}

return $fridays;
}

echo fridays_get('2011-02');

You can find a similar post about this: In PHP, how to know how many mondays have passed in this month uptil today?

like image 32
automaticAllDramatic Avatar answered Jan 18 '23 02:01

automaticAllDramatic