php - 如何用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...

知道如何获得这样的输出吗?

最佳答案

你可以使用 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"));
}

https://stackoverflow.com/questions/8616197/

相关文章:

perl - 如何在 Perl 中创建一个新文件?

r - 安装 Rstem 包的问题

python - 在 PYTHON 中使用 POUND SIGN 作为字符串?

php - 二进制 in_array 搜索

css - 当类名只是一个整数时,如何编写 CSS 选择器?

sql - oracle如何获取最新的员工记录?

c# - 每 2 分钟运行一次任务计划程序

r - R 中滞后的 xts 对象

objective-c - 使用 NSRegularExpression 将每个匹配项替换为方法的结

wix - 在 WIX 安装程序中检查 RAM