Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use PHP to list all the dates in a year?

Tags:

date

php

mktime

I'm trying to use PHP to create a script that searches all the days between now and one year's time and lists all the dates for Fridays and Saturdays. I was trying to use PHP's date() and mktime() functions but can't think of a way of doing this. Is it possible?

Thanks, Ben

like image 630
Ben Avatar asked Oct 28 '10 16:10

Ben


2 Answers

Here's how to do it in a cool way, with special thanks to strtotime's relative formats.

$friday = strtotime('Next Friday', time());
$saturday = strtotime('Next Saturday', time());
$friday = strtotime('+1 Week', $friday);
$saturday = strtotime('+1 Week', $saturday);

Of course you should tweak it to do exactly what you want, but that's beside the point I was trying to make.

Also note that strtotime will give you timestamps. To find out the date use:

date('Y-m-d', $friday)

Another thing to know is that Next <dayofweek> will exclude your current day from the search, so if you also want to include the current day you can do it like this:

$friday = strtotime('Next Friday', strtotime('-1 Day', time()));

And here's a full working script that does exactly what you wanted.

<?php
// prevent multiple calls by retrieving time once //
$now = time();
$aYearLater = strtotime('+1 Year', $now);

// fill this with dates //
$allDates = Array();

// init with next friday and saturday //
$friday = strtotime('Next Friday', strtotime('-1 Day', $now));
$saturday = strtotime('Next Saturday', strtotime('-1 Day', $now));

// keep adding days untill a year has passed //
while(1){
    if($friday > $aYearLater)
        break 1;
    $allDates[] = date('Y-m-d', $friday);
    if($saturday > $aYearLater)
        break 1;
    $allDates[] = date('Y-m-d', $saturday);

    $friday = strtotime('+1 Week', $friday);
    $saturday = strtotime('+1 Week', $saturday);
}

//XXX: debug
var_dump($allDates);

?>

Good luck, Alin

like image 76
Alin Purcaru Avatar answered Oct 02 '22 10:10

Alin Purcaru


With DateTime objects:

<?php

define('FRIDAY', 5);
define('SATURDAY', 6);

$from = new DateTime;
$to = new DateTime('+1 year');

for($date=clone $from; $date<$to; $date->modify('+1 day')){
    switch($date->format('w')){
        case FRIDAY:
        case SATURDAY:
            echo $date->format('r') . PHP_EOL;
    }
}

Update: I've added the $date=clone $from part to remark that objects in PHP/5 are no longer copied with the = operator but referenced.

like image 22
Álvaro González Avatar answered Oct 02 '22 08:10

Álvaro González