PHP创建DateTime,每天在2个日期之间进行特定日期



我需要在每月开始日期和结束日期之间创建一个日期时间。示例:

  • 特定的日子:04
  • 开始:2016-12-22
  • 结束:2017-03-06
  • 所需的输出:2016-01-04;2016-02-04;2016-03-04

我该怎么做?

您可以创建一个DatePeriod对象并迭代其以获取所需的所有日期:

$start = new DateTime('2016-12-22');
$end   = new DateTime('2017-03-06');
// Compute the occurrence on the same month as $start
$first = new DateTime();
$first->setDate($start->format('Y'), $start->format('m'), 4);
// If it is in the past of $start then the first occurrence is on the next month
if ($first < $start) {
    $first->add(new DateInterval('P1M'));
}
// Create a DatePeriod object that iterates between $first and $end
// in increments of 1 month
$period = new DatePeriod($first, new DateInterval('P1M'), $end);
// Run through the list, process each item
foreach ($period as $day) {
    echo($day->format('Y-m-d')."n");
}

我找到了它!以下代码对我有用:

$d1 = new DateTime("2016-12-22");
$d2 = new DateTime("2017-03-06");
$dd = '04';
if ($dd < $d1->format('d') ) {
    $d1->add(new DateInterval('P1M'));
    $date = $dd.'-'.$d1->format('m').'-'.$d1->format('Y');
} else {
    $date = $d1->format('Y').'-'.$d1->format('m').'-'.$dd;
}
$date = new DateTime($date);
print_r($date);echo('<br />');
while ($date->add(new DateInterval('P1M')) <= $d2){
    $d1->add(new DateInterval('P1M'));
    $date = $dd.'-'.$d1->format('m').'-'.$d1->format('Y');
    $date = new DateTime($date);
    print_r($date);echo('<br />');
}

最新更新