PHP实现时间格式转换,获取友好的时间显示
1.函数gmstrftime();
<?php /** * 时间友好显示 * @param int $time 时间戳 * @return string 友好时间字符串 * @author zhouzy */ function get_friendly_time($time) { //time=时间戳,timeCurr=当前时间,timeDiff=时间差,dayDiff=天数差,yearDiff=年数差 if (!$time) { return ''; } $timeCurr = time(); $timeDiff = $timeCurr - $time; $dayDiff = intval(date("z", $timeCurr)) - intval(date("z", $time)); $yearDiff = intval(date("Y", $timeCurr)) - intval(date("Y", $time)); if ($timeDiff < 60) { if ($timeDiff < 10) { return '刚刚'; } else { return floor($timeDiff) . "秒前"; } } elseif ($timeDiff < 3600) { //1小时内 return floor($timeDiff / 60) . "分钟前"; } elseif ($yearDiff == 0 && $dayDiff == 0) { //今天内 return '今天 ' . date('H:i', $time); } elseif ($yearDiff == 0) { //今年内 return date("m月d日 H:i", $time); } else { //正常显示 return date("Y-m-d H:i", $time); } } /** * 时间对比 * @param $time int 对比的时间(时间戳) * @param $nowTime int 目前时间(时间戳) * @return string */ function time_ago($time = 0, $nowTime = 0) { if (!$nowTime) $nowTime = time(); $dif = $nowTime - $time; if ($dif < 1) return '刚刚'; if ($dif < 60) return $dif . '秒前'; $dif = $dif / 60; if (1 <= $dif && $dif < 60) return (int)$dif . '分钟前'; $dif = $dif / 60; if (1 <= $dif && $dif < 24) return (int)$dif . '小时前'; //最多显示3天前 $dif = $dif / 24; if (1 <= $dif && $dif <= 3) return (int)$dif . '天前'; return date('m-d', $time); } /** * 友好的时间显示 */ function time_to_units($time) { $now_time = time(); $time_diff = $now_time - $time; $units = array( '31536000' => '年前', '2592000' => '月前', '86400' => '天前', '3600' => '小时前', '60' => '分钟前', '1' => '秒前', ); foreach ($units as $key => $value) { if ($time_diff > $key) { $num = (int)($time_diff / $key); $tips = $num . $value; break; } } return $tips; } /** * 计算持续时长 * (秒转换为天,小时,分钟) * @param int $second 秒数 * @return string $duration 5天10小时43分钟40秒 */ function secondTime($seconds=0){ $duration = ''; $seconds = (int) $seconds; if ($seconds <= 0) { return $duration.'0秒'; } list($day, $hour, $minute, $second) = explode(' ', gmstrftime('%j %H %M %S', $seconds)); $day -= 1; if ($day > 0) { $duration .= (int) $day.'天'; } if ($hour > 0) { $duration .= (int) $hour.'小时'; } if ($minute > 0) { $duration .= (int) $minute.'分钟'; } if ($second > 0) { $duration .= (int) $second.'秒'; } return $duration; }