After calculating a time difference, how can I determine if the diff is only minutes, or is it hours, or days, weeks, months, years...?
$now = new DateTime('now');
$expire_date = date('Y-m-d H:i:s', strtotime('+ 3 weeks'));
$expire_on = new DateTime($expire_date);
$time_left = $now->diff($expires_on);
*** pseudo code below showing what I am trying to do
if ($time_left < 1 hour)
display just minutes
elseif ($time_left < 1 day)
display hours & minutes
elseif ($time_left < 1 week)
display days, hours & minutes
elseif ($time_left < 1 month)
display weeks, days, hours & minutes
elseif ($time_left < 1 year)
display months, weeks, days, hours & minutes
endif
** end pseudo code
As I quickly learned, I need to clarify the question. I want to display ONLY the bare minimum info. For example: "39 minutes remaining" and not "0 days, 0 hours, 39 minutes remaining".
https://www.php.net/manual/en/class.dateinterval.php - there are properties in the DateInterval object (of which $time_left is one) for most of those, so you can test them and see if they're above 0. I suggest starting with the largest.
For example:
$now = new DateTime('now');
$expire_date = date('Y-m-d H:i:s', strtotime('+3 weeks'));
$expire_on = new DateTime($expire_date);
$time_left = $now->diff($expire_on);
echo format_interval($time_left);
function format_interval($time_left) {
$format_string = "";
$weeks = (int) ($time_left->d / 7);
$days = (int) ($time_left->d - ($weeks * 7));
if ($time_left->y > 0) $format_string = "%y year(s), %m month(s), $weeks week(s), $days day(s), %h hour(s) and %i minute(s)";
elseif ($time_left->m > 0) $format_string = "%m month(s), $weeks week(s), $days day(s), %h hour(s) and %i minute(s)";
elseif ($weeks > 0) $format_string = "$weeks week(s), $days day(s), %h hour(s) and %i minute(s)";
elseif ($time_left->d > 0) $format_string = "$days day(s), %h hour(s) and %i minute(s)";
elseif ($time_left->h > 0) $format_string = "%h hour(s) and %i minute(s)";
elseif ($time_left->i > 0) $format_string = "%i minute(s)";
else $format_string = "%s second(s)";
return $time_left->format($format_string);
}
Live demo: https://3v4l.org/BiYHD . Try adjusting the $expire_date
and test the results you get.
N.B. The DateInterval class doesn't support telling you the number of weeks, for some reason. Above I've assumed that dividing the number of days by 7 is sufficient to calculate that. You then have to recalculate the remaining days (once the days in the allocated weeks are subtracted).