如何用PHP生成每月天数?

时间:2011-12-23 12:40:32

标签: php

我试图像这样生成当月的日子

    $year = date('Y');
    $month = date('m');

    $dayCount = cal_days_in_month(CAL_GREGORIAN,$month,$year);

    for ($i = 1; $i <= $dayCount; $i++)
    {
        $tree_data->data[$i] = $year."-".$month."-".$i;
    }
    print "<pre>";
    print_r($tree_data);

给我输出像

stdClass Object
(
    [data] => Array
        (
            [1] => 2011-12-1
            [2] => 2011-12-2
            [3] => 2011-12-3
            [4] => 2011-12-4
            [5] => 2011-12-5
            [6] => 2011-12-6
            [7] => 2011-12-7
            [8] => 2011-12-8
            [9] => 2011-12-9
            [10] => 2011-12-10
            [11] => 2011-12-11
            [12] => 2011-12-12
            [13] => 2011-12-13
            [14] => 2011-12-14
            [15] => 2011-12-15
            [16] => 2011-12-16
            [17] => 2011-12-17
            [18] => 2011-12-18
            [19] => 2011-12-19
            [20] => 2011-12-20
            [21] => 2011-12-21
            [22] => 2011-12-22
            [23] => 2011-12-23
            [24] => 2011-12-24
            [25] => 2011-12-25
            [26] => 2011-12-26
            [27] => 2011-12-27
            [28] => 2011-12-28
            [29] => 2011-12-29
            [30] => 2011-12-30
            [31] => 2011-12-31
        )

)

我的问题是我希望像

一样得到1到9天
2011-12-01, 2011-12-02 etc...

任何想法如何得到这样的输出?

5 个答案:

答案 0 :(得分:6)

您可以使用sprintf

sprintf('%1$02d', $i);

另一种方法可能是使用DateTime对象:

$aDates = array();
$oStart = new DateTime('2011-12-01');
$oEnd = clone $oStart;
$oEnd->add(new DateInterval("P1M"));

while($oStart->getTimestamp() < $oEnd->getTimestamp()) {
  $aDates[] = $oStart->format('Y-m-d');
  $oStart->add(new DateInterval("P1D"));
}

答案 1 :(得分:3)

这应该足够了。 :)

$year = date('Y');
$month = date('m');

$dayCount = cal_days_in_month(CAL_GREGORIAN,$month,$year);

for ($i = 1; $i <= $dayCount; $i++)
{
    $tree_data->data[$i] = $year."-".$month."-".str_pad($i, 2, "0", STR_PAD_LEFT);
}
$ret = implode(", ", $tree_data->data);

答案 2 :(得分:2)

答案 3 :(得分:1)

$year = date('Y');
$month = date('m');

$dayCount = cal_days_in_month(CAL_GREGORIAN,$month,$year);

for ($i = 1; $i <= $dayCount; $i++)
{
    $tree_data->data[$i] = $year."-".$month."-".(($i < 10)?'0'.$i:$i);
}
print "<pre>";
print_r($tree_data);

答案 4 :(得分:1)

正如其他答案建议您可以有条件地将0添加到当天,或者这是另一种方式来处理这些事情以防万一。

    $startMonth = date('Y-m-01');
    $endMonth = date('Y-m-t');
    $i = 0;
    while(strtotime($startMonth) <= strtotime($endMonth)){
       $tree_date->date[$i] = $startMonth;
       $startMonth = date('Y-m-d', strtotime($startMonth.' +1 days'));
       $i++;
    }

   print_r($tree_date);