0

Good day.

Ive been trying to get the days from the current day using Carbon in Laravel. So if today is the December 20 I want to get an array with:

December 20, 2018
December 21, 2018
December 22, 2018
December 23, 2018
December 24, 2018

I want to do it for 2 weeks or maybe even 3 weeks. This is what I got so far.

$currentdate = Carbon::now()->format('m/d/Y');
$ts = strtotime($currentdate);

$year = date('o', $ts);
$week = date('W', $ts);

$datearray = [];
for($i = 1; $i <= 7; $i++) {
   $ts = strtotime($year.'W'.$week.$i);
   array_push($datearray,date("m/d/Y", $ts));
}

The code above gives me for the week from the starting of the week and not from the day going forward.

Slygoth
  • 333
  • 6
  • 17
  • Look into this answer [PHP Carbon, get all dates between date range?](https://stackoverflow.com/a/50854594/3226121) – ljubadr Dec 20 '18 at 20:11
  • Carbon has some great methods for getting and settings dates, such as addDay() and toDateString. It might be easier than what you're trying to do here. Check out their [docs here](https://carbon.nesbot.com/docs/) – aynber Dec 20 '18 at 20:15
  • in carbon use `addDays(1);` in a loop, your mixing in legacy strtotime for some reason –  Dec 20 '18 at 20:16

2 Answers2

0

Try this,

$datearray = [];
for($i = 0; $i < 7; $i++) {
   array_push($datearray, date('F d, Y', strtotime($i == 0 ?'today UTC':'today +'.$i.'day')));
   //push to array as 'December 20, 2018'
}

enjoy coding~! :)

JsWizard
  • 1,663
  • 3
  • 21
  • 48
  • why use carbon ignore all its methods and revert to strtotime? –  Dec 20 '18 at 20:28
  • @tim, It has a lot of useful built-in functions and is easy to develop than original function of PHP Data.:) https://carbon.nesbot.com/docs/" – JsWizard Dec 20 '18 at 20:48
  • exactly, so why not use them? –  Dec 20 '18 at 20:53
  • @tim, you can use that in your code if you want more performance, built-in function also included PHP methods in internal :) – JsWizard Dec 20 '18 at 21:02
  • if that's why you think why are you using `Carbon::now` ? you cant have it both ways. –  Dec 20 '18 at 21:11
  • @tim, please check this, I learned PHP `Date` is better than `Carbon` because of you. thanks:p https://stackoverflow.com/questions/43113905/which-is-faster-php-date-functions-or-carbon – JsWizard Dec 21 '18 at 08:37
0

If you are already using Carbon, use its power!

use \Carbon\Carbon;

// how many days you want in your array
$count = 7;
$dates = [];
$date = Carbon::now();
for ($i = 0; $i < $count; $i++) {
    $dates[] = $date->addDay()->format('F d, Y');
}

// Show me what you got
print_r($dates);

Output is:

Array
(
    [0] => December 22, 2018
    [1] => December 23, 2018
    [2] => December 24, 2018
    [3] => December 25, 2018
    [4] => December 26, 2018
    [5] => December 27, 2018
    [6] => December 28, 2018
)
Don't Panic
  • 13,965
  • 5
  • 32
  • 51