PHP getting month dates and placing into array

2019-08-28 17:40发布

问题:

Today I found this function that says how many days were in a month cal_days_in_month(). But what I am wanting to do is list all the days into array, something like this.

$days = array(
"2012-11-01","2012-12-01","2012-13-01"...etc
)

Could someone point me into the right direction?

Kind regards Frank!

回答1:

$start    = new DateTime('first day of this month');
$end      = new DateTime('first day of next month');
$interval = DateInterval::createFromDateString('1 day');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt)
{
  echo $dt->format("l Y-m-d") . PHP_EOL;
}

See it in action

Reference

  • DateTime
  • DatePeriod
  • DateInterval


回答2:

 $fromdate=strtotime(date("Y-m-d",mktime(0, 0, 0, $month, '01', $year)));
    $todate=strtotime(date("Y-m-t",mktime(0, 0, 0, $month, '01', $year)));

        for($i=$fromdate;$i<=$todate;$i++)
        {
        $i=$i+84600;
        echo     $nextdate[]=date('Y-m-d',$i);
        }