Welcome to stackoverflow :-)
PHP has a native DateTime class which allows you to perform date manipulations and date-formatting.
In your specific case you could start to convert your two dates into objects and then reformat it into your expected format.
Here is an example:
$date = DateTime::createFromFormat('d/m/Y', $startString);
With this in mind we can now create a function which will check your requirements and return the string on your custom format.
function my_date_range(DateTime $start, DateTime $end)
{
$sameYear = $start->format('Y') === $end->format('Y');
$sameMonth = $sameYear && $start->format('m') === $end->format('m');
$sameDay = $sameMonth && $start->format('d') === $end->format('d');
if ($sameDay) {
return $start->format('d M Y');
}
if ($sameMonth) {
return sprintf('%s to %s', $start->format('d'), $end->format('d M Y'));
}
if ($sameYear) {
return sprintf('%s to %s', $start->format('d M'), $end->format('d M Y'));
}
return sprintf("%s to %s", $start->format('d M Y'), $end->format('d M Y'));
}
Below you'll find my example dates and usage:
var_dump(
my_date_range(DateTime::createFromFormat('d/m/Y', '11/2/2020'), DateTime::createFromFormat('d/m/Y', '26/2/2020')),
my_date_range(DateTime::createFromFormat('d/m/Y', '26/2/2020'), DateTime::createFromFormat('d/m/Y', '5/3/2020')),
my_date_range(DateTime::createFromFormat('d/m/Y', '29/12/2020'), DateTime::createFromFormat('d/m/Y', '2/1/2021')),
my_date_range(DateTime::createFromFormat('d/m/Y', '2/1/2021'), DateTime::createFromFormat('d/m/Y', '2/1/2021')),
)
Result:
string(17) "11 to 26 Feb 2020"
string(21) "26 Feb to 05 Mar 2020"
string(26) "29 Dec 2020 to 02 Jan 2021"
string(11) "02 Jan 2021"