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".
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:
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).