简体   繁体   中英

Creating a DatePeriod array with future dates using CArbon

I have an Courses model that contains a start_date column back in my DB. From this start_date I want to generate an array of the next 6 weeks for that day of the week.

eg, If the start_date is Monday, December 4th, 2017, I want to generate an array with the next 6 preceding Mondays, where the array also includes the original start_date as well as the 6th date.

Heres the logic Ive attempted in my model:

use Carbon\Carbon;
use Carbon\CarbonInterval;

class Product {




    public function getRange($date) {
      return new \DatePeriod(
        Carbon::parse($date),
        CarbonInterval::week(),
        Carbon::parse($date)->addWeeks(6)
      );
    }

}

However when i try outputting this in my template i get the following error:

An exception has been thrown during the rendering of a template ("Object of class DatePeriod could not be converted to string").

suggestions?

Your exception tells me that you are trying to output an object using either echo , print``or a template engine method. You are essentially using a print``or a template engine method. You are essentially using a DatePeriod``object as string. Instead it should be used like this:

$startDate = new DateTime();
$endDate = new DateTime();
$endDate->modify('+7 days');

$interval = new DateInterval('P1D');
$dateRange = new DatePeriod($startDate, $interval ,$endDate);

Your template:

<?php foreach($dateRange as $date): ?>
    <?= $date->format("Ymd"); ?><br />
<?php endforeach; ?>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM