0

I have a form that the user should fill two dates.I want to display dates between those selected dates like

  June 11
  June 12
  June 13
  June 14
  June 15
  Jun  16
  Jun  17

in my action.php

$dateTo = $r->getParameter("date_to", date('Y-m-d'));
$dateFrom = $r->getParameter("date_from", date('Y-m-d', strtotime('7 days ago', strtotime($dateTo))));

$dateRange = new DatePeriod(DateTime::createFromFormat('Y-m-d',$dateTo), new DateInterval('P1D'), DateTime::createFromFormat('Y-m-d',$dateFrom));

then in my templates, I tried

foreach $dateRange as $date {echo $date}

Whats the correct way to display those date? var_dump outputs like

 object(DatePeriod)[62]
 public 'start' => 
 object(DateTime)[21645]
  public 'date' => string '2015-05-20 16:56:21' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Asia/Manila' (length=11)
 public 'current' => null
 public 'end' => 
 object(DateTime)[21656]

and I tried

<?php foreach($dateRange as $r):?>
<?php echo $r->format('Y-m-d') ?>
<?php endforeach ?>

But nothing displayed in my table

2 Answers2

1

According to the PHP doc DatePeriod implements the Traversable interface. So you can use it like an array and loop with a foeeach over it:

/** @var DateTime[] $dateRange */
$dateRange = new DatePeriod(...);

foreach($dateRange as $date) {
    $date->format(...);
}

What is not mentioned in the official PHP doc is that you get an "array" of DateTime objects.

TiMESPLiNTER
  • 5,741
  • 2
  • 28
  • 64
0

You need to use format. Like this:

echo $date->format("Ymd") . "<br>";

blockhead
  • 9,655
  • 3
  • 43
  • 69