Skip to content

Instantly share code, notes, and snippets.

@viko16
Created January 14, 2015 02:07
Show Gist options
  • Save viko16/1385869ad6461c2f1c2f to your computer and use it in GitHub Desktop.
Save viko16/1385869ad6461c2f1c2f to your computer and use it in GitHub Desktop.
最高级别的时间差(年、月、日、时、分、秒) #php
/**
* Timespan
*
* 返回最高级别的时间差(年、月、日、时、分、秒)
*
* @access public
* @param integer a number of seconds
* @param integer Unix timestamp
* @return integer
*/
if (!function_exists('timespan')) {
function timespan($seconds = 1, $time = '')
{
if (!is_numeric($seconds)) {
$seconds = 1;
}
if (!is_numeric($time)) {
$time = time();
}
if ($time <= $seconds) {
$seconds = 1;
} else {
$seconds = $time - $seconds;
}
$str = '';
$years = floor($seconds / 31536000);
if ($years > 0) {
$str .= $years . '年前 ';
return $str;
}
$seconds -= $years * 31536000;
$months = floor($seconds / 2628000);
if ($years > 0 OR $months > 0) {
if ($months > 0) {
$str .= $months . '月前';
}
$seconds -= $months * 2628000;
return $str;
}
$weeks = floor($seconds / 604800);
if ($years > 0 OR $months > 0 OR $weeks > 0) {
if ($weeks > 0) {
$str .= $weeks . '周前';
}
$seconds -= $weeks * 604800;
return $str;
}
$days = floor($seconds / 86400);
if ($months > 0 OR $weeks > 0 OR $days > 0) {
if ($days > 0) {
$str .= $days . '天前';
}
$seconds -= $days * 86400;
return $str;
}
$hours = floor($seconds / 3600);
if ($days > 0 OR $hours > 0) {
if ($hours > 0) {
$str .= $hours . '小时前';
}
$seconds -= $hours * 3600;
return $str;
}
$minutes = floor($seconds / 60);
if ($days > 0 OR $hours > 0 OR $minutes > 0) {
if ($minutes > 0) {
$str .= $minutes . '分钟前';
}
$seconds -= $minutes * 60;
return $str;
}
if ($str == '') {
$str .= $seconds . '秒前';
}
return $str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment