Laravel get all dates between a date range


Image title

Some time we need to get all the individual calendar dates between two calendar date range in our code, such a scenario like time sheet generation , or payroll sheet generation, etc... You can utilize PHP carbon library which is already being shipped with Laravel framework,

in the following example I have two dates variable,  $starDate and $endDate , which are beginning of a month and End of a month respectively. first I converted both string dates to Carbon Objects to utilize carbon library methods in my code,
I am using a while loop to scroll through the dates by adding 1 day to startDate in the end of the loop, and while loop will continue to execute until it become equal to endDate, this condition is evaluated by the $startDate->lte carbon object method , lte means less than or equal,

$startDate = new Carbon('2018-01-01');
$endDate = new Carbon('2018-01-31');
$all_dates = array();
while ($startDate->lte($endDate)){
  $all_dates[] = $startDate->toDateString();

  $startDate->addDay();
}
print_r($all_dates);

The purpose of the post is not to discuss about the Carbon library, but you may read my another post about Laravel Carbon Library in the following link.

https://www.techalyst.com/links/read/83/working-with-datetime-in-laravel-52-using-php-carbon-library

Written by Akram Wahid 5 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}