Heim > Fragen und Antworten > Hauptteil
Wie kann ich nach der Berechnung des Zeitunterschieds feststellen, ob der Unterschied nur Minuten, Stunden oder Tage, Wochen, Monate, Jahre ... beträgt?
$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 ** 结束伪代码
Wie ich schnell lernte, musste ich Dinge klären. Ich möchte nur minimale Informationen anzeigen. Beispiel: „Noch 39 Minuten“ statt „0 Tage, 0 Stunden, noch 39 Minuten“.
P粉5614384072023-09-14 10:53:04
https://www.php.net/manual/en/class.dateinterval.php - DateInterval对象中有一些属性(其中$time_left是其中之一),因此您可以测试它们并查看它们是否大于0。我建议从最大的开始。
例如:
$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); }
在线演示:https://3v4l.org/BiYHD。尝试调整$expire_date
并测试您获得的结果。
注意:由于某种原因,DateInterval类不支持告诉您周数。上面我假设将天数除以7足以计算出周数。然后必须重新计算剩余的天数(减去分配周中的天数)。