I have an array that indicates the number of the weekday for example this array:
[1, 3, 5]
Indicates Monday, Wednesday and Friday, given a date range how can I get the date of all mondays, wednesdays and friday between that range.
I'm using Laravel with Carbon.
CodePudding user response:
Check this Code:
function weekDaysBetween($requiredDays, $start, $end){
$startTime = Carbon::createFromFormat('d-m-Y', $start);
$endTime = Carbon::createFromFormat('d-m-Y', $end);
$result = [];
while ($startTime->lt($endTime)) {
if(in_array($startTime->dayOfWeek, $requiredDays)){
array_push($result, $startTime->copy());
}
$startTime->addDay();
}
return $result;
}
And you can call it like:
weekDaysBetween([1,2, 3], "01-09-2021", "01-10-2021")
And the reult would be like:
[
"2021-09-01T22:02:21.000000Z",
"2021-09-06T22:02:21.000000Z",
"2021-09-07T22:02:21.000000Z",
"2021-09-08T22:02:21.000000Z",
"2021-09-13T22:02:21.000000Z",
"2021-09-14T22:02:21.000000Z",
"2021-09-15T22:02:21.000000Z",
"2021-09-20T22:02:21.000000Z",
"2021-09-21T22:02:21.000000Z",
"2021-09-22T22:02:21.000000Z",
"2021-09-27T22:02:21.000000Z",
"2021-09-28T22:02:21.000000Z",
"2021-09-29T22:02:21.000000Z"
]