0

I'm able to show days from current date to next 3 months with this code:

$begin = new DateTime();
$end = new DateTime(date('Y-m-d', strtotime('+3 months', strtotime(date("d-m-Y")))));
$interval = DateInterval::createFromDateString('1 day');
$days = new DatePeriod($begin, $interval, $end);

foreach ( $days as $day ) {
    ...
}

I feel the code can be shortened especially for $end. Could you help?

Oh, I also want to get previous 3 months. I changed '+3 months' to '-3 months'but no luck. Any ideas?

Jeaf Gilbert
  • 11,495
  • 19
  • 78
  • 105

2 Answers2

5
$begin    = new DateTime();
$end      = new DateTime('+ 3 months');
$interval = DateInterval::createFromDateString('1 day');
$days     = new DatePeriod($begin, $interval, $end);
foreach ( $days as $day ) {
    var_dump($day);
}

$begin    = new DateTime('- 3 months'); // '3 months ago' should also work
$end      = new DateTime();
$interval = DateInterval::createFromDateString('1 day');
$days     = new DatePeriod($begin, $interval, $end);
foreach ( $days as $day ) {
    var_dump($day);
}
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
1

For your first question, you can directly write

$end = new DateTime('+3 months');

To go back 3 months, use3 months ago instead of -3 months.

joni
  • 5,402
  • 1
  • 27
  • 40