PHP格式化时长,转换为 年/月/星期/天/时/分/秒
/** * 格式化时长(年/月/星期/天/时/分/秒) * * @param string $startTime 开始时间,如:2020-06-21 17:07:34 * @param string $endTime 结束时间,如:2020-06-21 23:08:42 * @return string */ function formatDuration($startTime = '', $endTime = ''){ if (empty($startTime)) { return ''; } if (empty($endTime)) { $endTime = date('Y-m-d H:i:s'); } $startTime = strtotime($startTime); $endTime = strtotime($endTime); $duration = $endTime - $startTime; $format = [ '31536000' => '年', '2592000' => '个月', '604800' => '星期', '86400' => '天', '3600' => '小时', '60' => '分钟', '1' => '秒' ]; foreach ($format as $k => $v) { if (0 != $c = floor($duration / (int)$k)) { return '<span class="color-red">' . $c . ' </span>' . $v; } } return ''; }