PHP Dates are wonderful things +1 year
for example. However I’m getting myself in a bit of a mess. I have three dates spanning two months and I want to make an elegant string
"28, 29 February & 1 March" from an array of 3 dates in the form YYYYMMDD
. The exact number of dates is not known, minimum 1 probable max 4
Other than some rather tortuous str_replace
manipulation, how do I get from the output of this to my desired format?
NB: no more than 2 months, maybe all in one month.
$dates_array = ['20240228', '20240229', '20240301'];
foreach ($dates_array as $date) :
$datetimes[] = new DateTime($date);
endforeach;
// print_r($datetimes);
foreach ($datetimes as $key=>$date) :
$month = $date->format('F');
$day = $date->format('j');
$date_array[]= $day." ".$month." & ";
endforeach;
$date_string = join( ' ', $date_array ) ;
echo $date_string;
// 28 February & 29 February & 1 March &
5
Answers
You can try this small script, I advise you to make a nice test to be sure it works with different use cases.
PS: the spread operator (
...
) has been implemented in PHP 7.4:As you loop through the
$datetimes
you’d have to check whether the next value in the list is in the same month or not, in order to know whether or not to including the month name in the formatted output for that date or not.This is one way to do that. The broad assumption is that the dates will always be supplied in ascending order, but it does also check if the next date is in the same year, as well as the same month, in case there’s a large gap between dates.
Live demo: https://3v4l.org/tWrhe
I managed to create this:
This returns:
It is not all that complicated. I did however put everything in a function because I would otherwise have to create quite a few global variables, and that’s seen as bad practice.
For a demo see: https://3v4l.org/gUWih
One more possible way to approach this, grouping the dates by month in an array first, and joining it all together with
implode
:https://3v4l.org/6snHe
Obviously won’t work if you had dates for the same month in different years, but I guess that’s not a requirement(?).
Here is another stab at this:
Iterate over the dates, in each iteration check if previous date is contiguous and belongs to same month.