Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the date of All Fridays in PHP

Tags:

date

php

I looking to list the date of all fridays in a given year using PHP.

After reading php.net date and maketime function, I do not see how I should start...

Can you guys give me a hand on this ?

Thanks, Crak

like image 353
Crak Avatar asked Dec 04 '22 07:12

Crak


1 Answers

I believe DatePeriod might have been made for a problem like this.

<?php
function getFridays($year, $format, $timezone='UTC')
{
    $fridays = array();
    $startDate = new DateTime("{$year}-01-01 Friday", new DateTimezone($timezone));
    $year++;
    $endDate = new DateTime("{$year}-01-01", new DateTimezone($timezone));
    $int = new DateInterval('P7D');
    foreach(new DatePeriod($startDate, $int, $endDate) as $d) {
        $fridays[] = $d->format($format);
    }

    return $fridays;
}

$fridays = getFridays('2010', 'F j, Y, g:i a T', 'America/New_York');
print_r($fridays);
?>

Output

Array
(
    [0] => Friday, January 1, 2010
    [1] => Friday, January 8, 2010
    [2] => Friday, January 15, 2010
    [3] => Friday, January 22, 2010
    [4] => Friday, January 29, 2010
    [5] => Friday, February 5, 2010
    [6] => Friday, February 12, 2010
    [7] => Friday, February 19, 2010
    [8] => Friday, February 26, 2010
    [9] => Friday, March 5, 2010
    [10] => Friday, March 12, 2010
    [11] => Friday, March 19, 2010
    [12] => Friday, March 26, 2010
    [13] => Friday, April 2, 2010
    [14] => Friday, April 9, 2010
    [15] => Friday, April 16, 2010
    [16] => Friday, April 23, 2010
    [17] => Friday, April 30, 2010
    [18] => Friday, May 7, 2010
    [19] => Friday, May 14, 2010
    [20] => Friday, May 21, 2010
    [21] => Friday, May 28, 2010
    [22] => Friday, June 4, 2010
    [23] => Friday, June 11, 2010
    [24] => Friday, June 18, 2010
    [25] => Friday, June 25, 2010
    [26] => Friday, July 2, 2010
    [27] => Friday, July 9, 2010
    [28] => Friday, July 16, 2010
    [29] => Friday, July 23, 2010
    [30] => Friday, July 30, 2010
    [31] => Friday, August 6, 2010
    [32] => Friday, August 13, 2010
    [33] => Friday, August 20, 2010
    [34] => Friday, August 27, 2010
    [35] => Friday, September 3, 2010
    [36] => Friday, September 10, 2010
    [37] => Friday, September 17, 2010
    [38] => Friday, September 24, 2010
    [39] => Friday, October 1, 2010
    [40] => Friday, October 8, 2010
    [41] => Friday, October 15, 2010
    [42] => Friday, October 22, 2010
    [43] => Friday, October 29, 2010
    [44] => Friday, November 5, 2010
    [45] => Friday, November 12, 2010
    [46] => Friday, November 19, 2010
    [47] => Friday, November 26, 2010
    [48] => Friday, December 3, 2010
    [49] => Friday, December 10, 2010
    [50] => Friday, December 17, 2010
    [51] => Friday, December 24, 2010
    [52] => Friday, December 31, 2010
)
like image 102
Herbert Avatar answered Dec 18 '22 13:12

Herbert