search

Home  >  Q&A  >  body text

Determine the maximum interval of time difference: PHP implementation in minutes, hours, days, weeks, etc.

After calculating the time difference, how do I determine whether the difference is only minutes, 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);

*** 伪代码如下所示,展示了我想要实现的功能
if ($time_left < 1 小时)
   显示分钟
elseif ($time_left < 1 天)
   显示小时和分钟
elseif ($time_left < 1 周)
   显示天、小时和分钟
elseif ($time_left < 1 月)
   显示周、天、小时和分钟
elseif ($time_left < 1 年)
   显示月、周、天、小时和分钟
endif
** 结束伪代码

As I quickly learned, I needed to clarify the question. I only want to display minimal information. For example: "39 minutes remaining" instead of "0 days, 0 hours, 39 minutes remaining".

P粉287726308P粉287726308500 days ago631

reply all(1)I'll reply

  • P粉561438407

    P粉5614384072023-09-14 10:53:04

    https://www.php.net/manual/en/class.dateinterval.php - There are some properties in the DateInterval object ($time_left is one of them) so you can test them and see if they are greater than 0. I recommend 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);
    }

    Online demonstration: https://3v4l.org/BiYHD. Try adjusting $expire_date and test the results you get.

    NOTE: For some reason, the DateInterval class does not support telling you the week number. Above I assume dividing the number of days by 7 is enough to calculate the number of weeks. The remaining days must then be recalculated (minus the number of days in the distribution week).

    reply
    0
  • Cancelreply