I’m using Laravel 9 to create lessons scheduler,
I tried that way but Im little lost,
$free_time_frame = [[]]; // nested array here
$start = new DateTime("2023-01-01");
$end = new DateTime("2023-12-31");
$interval = new DateInterval("P1D"); // 1 month interval
$period = new DatePeriod($start, $interval, $end);
$seasons = ["2023-02-01", "2023-02-13"];
foreach ($period as $date) {
if (in_array($date->format("Y-m-d"), $seasons)) {
// Skip the rest of the loop if the current month is in the $seasons array
$free_time_frame[] = []; // append nested array
continue;
}
// Set the start date to the first day of the month
$start_date = new DateTime($date->format("Y-m-01"));
// Set the end date to the last day of the month
$end_date = new DateTime($date->format("Y-m-t"));
// Calculate the number of days between the start and end dates
$diff = $start_date->diff($end_date);
$days = $diff->days + 1; // Add 1 to include the end date
// use the latest nested array
}
I’m booking $seasons
I would like to have an array of the free days before "2023-02-01"
and days after "2023-02-13"
like that :
Expected Result
[
[
"2023-01-01",
"2023-01-02",
"2023-01-03",
"..."
"2023-01-31",
]
[
"2023-02-14",
"2023-02-15",
"2023-02-16",
"2023-02-14",
"and so on util the end of the year"
]
]
Thanks for the help in advance
3
Answers
Okay, so I think I understand, that you want to get all dates between a range of dates, then exclude a specific range of date.
You can do it like this:
This will return an array of the following results:
Notice here that it skipped over from
2023-01-03
to2023-01-06
You can format this as you like by changing the line of
$date->format('d-m-Y')
to represent the results the way you want it, you can even remove the format to return a carbon array, which you can parse as you like somewhere else.And you can go one step further, and have multiple
excludedDates
, and check for themin_array
Hopefully this helps, add a comment if you want further clarifications or modifications.
To calculate free time from
$seasons
that doesn’t include in-between time period, it is just the everything before your first element of your seasons array and everything after last element of your seasons array.So, achieving this is just running 2 loops of DatePeriod in those ranges.
Online Fiddle
I think you can do the following:
The code above will achieve your expected result
I hope this can help you.