we can get Date Difference using diff
method of DateTime
class.
I wrote common function for that. just you need to pass Date/DateTime String format
or instance of DateTime class
<?php
$currentDate = '2022-07-27';
// $nextDate = '2022-07-27';
// $nextDate = '2022-07-28';
$nextDate = '2022-07-29';
echo getDateToTodayTomorrowFormat($nextDate, $currentDate);
/**
* get Date format to number of Days difference Format ('Today', 'Tomorrow', '2 days later', '3 days later' etc.)
*
* @param string|\DateTime $nextDate // eg. pass Object of DateTime class "OR" Date/Date-Time string (format :- 'Y-m-d', 'Y/m/d', 'Y-m-d H:i:s')
* @param string|\DateTime $currentDate // eg. pass Object of DateTime class "OR" Date/Date-Time string (format :- 'Y-m-d', 'Y/m/d', 'Y-m-d H:i:s')
* @return string
*
* Date/Date-Time string must be in format of standard formats which are supported by \DateTime::class (https://www.php.net/manual/en/class.datetime.php)
*
* ****
* # Input > Output :-
* $currentDate = '2022-07-27';
*
* case 1:- $nextDate = '2022-07-27', `then OUTPUT :- "Today"` \
* case 2:- $nextDate = '2022-07-28', `then OUTPUT :- "Tomorrow"` \
* case 3:- $nextDate = '2022-07-29', `then OUTPUT :- "2 days later"`
*/
function getDateToTodayTomorrowFormat($nextDate, $currentDate)
{
if (is_string($nextDate)) {
$nextDate = new \DateTime($nextDate);
}
if (is_string($currentDate)) {
$currentDate = new \DateTime($currentDate);
}
$interval = $currentDate->diff($nextDate);
// $days = $interval->format('%r %d'); // returns like "- 1", "0", "+ 1"
$days = $interval->days; // returns only 0 & int difference
if($days === 0) {
return 'Today';
} else if($days === 1) {
return 'Tomorrow';
} else {
return $days . ' days later';
}
}
?>
for more details see this stackoverflow question