cwd
cwd

Reputation: 54756

How to list dates in yyyy_mm format with PHP using a loop?

What's the cleanest way to use a loop in PHP to list dates in the following way?

2011_10
2011_09
2011_08
2011_07
2011_06
...
2010_03
2009_02
2009_01
2009_12
2009_11

The key elements here:

Had to make a few tweaks to the solution:

    // Set timezone
    date_default_timezone_set('UTC');

    // Start date
    $date = date('Y').'-'.date('m').'-01';
    // End date
    $end_date = '2009-1-1';

    while (strtotime($date) >= strtotime($end_date))
    {
        $date = date ("Y-m-d", strtotime("-1 month", strtotime($date)));
        echo substr($date,0,7);
        echo "\n";
    }

Upvotes: 1

Views: 897

Answers (3)

salathe
salathe

Reputation: 51950

PHP 5.3 introduces some great improvements to date/time processing in PHP. For example, the first day of, DateInterval and DatePeriod being used below.

$start    = new DateTime('first day of this month');
$end      = new DateTime('2009-11-01');
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    echo $date->format('Y_m') . PHP_EOL;
}

Upvotes: 0

Chuck F
Chuck F

Reputation: 1

This is what im guessing your asking for cause it doesnt really make sense......

$startmonth = date("m");
$endmonth = 7;
$startyear = date("Y");
$endyear = 2012;

//First for loop to loop threw years
for($i=$startyear; $i<=$endyear; $i++, $startmonth=0) {
    //Second for loop to loop threw months
    for($o=$startmonth; $o<=12; $o++) {
        //If statement to check and throw stop when at limits
        if($i == $endyear && $o <= $endmonth)
            echo $i."_".$o."<br/>";
        else
            break;
    }
}

Will output:
2012_0
2012_1
2012_2
2012_3
2012_4
2012_5
2012_6
2012_7

Upvotes: 0

lukas.pukenis
lukas.pukenis

Reputation: 13597

Maybe this little code does the thing? : more complicated situations.

    <?php
        // Set timezone
        date_default_timezone_set('UTC');

        // Start date
        $date = '2009-12-06';
        // End date
        $end_date = '2020-12-31';

        while (strtotime($date) <= strtotime($end_date)) {
            echo "$date\n";
            $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
        }

 ?>

The credit goes to: http://www.if-not-true-then-false.com/2009/php-loop-through-dates-from-date-to-date-with-strtotime-function/

Upvotes: 1

Related Questions