In PHP, this example return all dates between two dates in an array.
The task is to return all the dates in an array given two dates (start date and end date).
This function returns array-formatted data in two date ranges.
So let’s get started with the next step.
Example : 1
This example, use date interval class which stores fixed amount of time (in years, months, days, hours etc) or relative time string in the format that DateTime.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
// Declare two dates
$start = '01-11-2022';
$end = '05-11-2022';
$format = 'Y-m-d';
// Declare an empty array
$array = array();
// Variable that store the date interval
// of period 1 day
$interval = new DateInterval('P1D');
$realEnd = new DateTime($end);
$realEnd->add($interval);
$period = new DatePeriod(new DateTime($start), $interval, $realEnd);
// Use loop to store date into array
foreach ($period as $date) {
$array[] = $date->format($format);
}
// Display the dates in array format
dd($array);
}
}
Example : 2
This example use strtotime() function which is used to convert an English textual date-time description to a UNIX timestamp. It returns a timestamp on success, False otherwise.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
// Declare two dates
$Date1 = '01-11-2022';
$Date2 = '05-11-2022';
// Declare an empty array
$array = array();
// Use strtotime function
$Variable1 = strtotime($Date1);
$Variable2 = strtotime($Date2);
// Use for loop to store dates into array
// 86400 sec = 24 hrs = 60*60*24 = 1 day
for ($currentDate = $Variable1; $currentDate <= $Variable2; $currentDate += (86400)) {
$Store = date('Y-m-d', $currentDate);
$array[] = $Store;
}
// Display the dates in array format
dd($array);
}
}
All the best nerd.