0

I want to get all the dates between two given specific dates which will be changing dynamically according to the user requirements.

This works fine for me :

$begin = new DateTime( '2018-07-01' ); 
$end = new DateTime( '2018-08-10' );
$end = $end->modify( '+1 day' ); 
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

$dates = [];

foreach($daterange as $date){
    array_push($dates,$date->format('Y-m-d'));
}

return $dates;

But this gives me NULL array when I insert dates dynamically. For example,

$begin = new DateTime($request->date1); 
$end = new DateTime(today()); 
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

$dates = [];

foreach($daterange as $date){
    array_push($dates,$date->format('Y-m-d'));
}

return dates;

I have tried many inputs like storing today's date in a variable, changing it's format and then using that variable as an input. I tried changing date variable to string using (string) function and also I have used Carbon classes for dates, but somehow I am making mistake using DateTime, DateInterval and DatePeriod as I don't know the basics of them.

I need to get all the dates between two specific dates for charts in my admin panel.

Shreeraj
  • 758
  • 1
  • 9
  • 27
  • check `$request->date1` format and debug code like `echo $begin` & `echo $end` – Bilal Ahmed Aug 11 '18 at 05:52
  • 1
    Sir, I tried this $present = Carbon::now()->toDateString(); and then $begin = new DateTime( $present ); but I am getting this error {msg: "Object of class DateTime could not be converted to string 32", status: 0} and even without toDateString function, I am getting the same error. – Shreeraj Aug 11 '18 at 05:58
  • if you got empty array it may be because your interval is greater than the gap between your start date and your end date...You need to check wether or not $start!==$end and $end-$start>Interval... – Elementary Aug 11 '18 at 07:35
  • I checked it, $interval is fine. but still I am getting null array – Shreeraj Aug 11 '18 at 18:12

1 Answers1

1

Finally got the solution for this question. It worked by converting the dates to UNIX timestamp. Here's the code, how it worked:

$date_from = "2018-07-01";   
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp  

// Specify the end date. This date can be any English textual format  
$date_to = strtotime(today()); // Convert date to a UNIX timestamp  

$dates = [];

// Loop from the start date to end date and output all dates inbetween  
for ($i=$date_from; $i<=$date_to; $i+=86400) {  
    array_push($dates,date("Y-m-d", $i));  
}

return $dates;

Here is the reference where I found this solution, hope this helps others too.

Shreeraj
  • 758
  • 1
  • 9
  • 27