首页 >php教程 >PHP源码 >php时间友好格式化

php时间友好格式化

PHP中文网
PHP中文网原创
2016-05-25 17:13:421246浏览

[PHP]代码 

<?php

class DateFormat
{
	private static $_DIFF_FORMAT = array(
		&#39;DAY&#39; 			=> &#39;%s天前&#39;,
		&#39;DAY_HOUR&#39;		=> &#39;%s天%s小时前&#39;,
		&#39;HOUR&#39; 			=> &#39;%s小时&#39;,
		&#39;HOUR_MINUTE&#39; 	=> &#39;%s小时%s分前&#39;,
		&#39;MINUTE&#39; 		=> &#39;%s分钟前&#39;,
		&#39;MINUTE_SECOND&#39;	=> &#39;%s分钟%s秒前&#39;,
		&#39;SECOND&#39;		=> &#39;%s秒前&#39;,
	);

	/**
	 * 友好格式化时间
	 * 
	 * @param int 时间
	 * @param array $formats
	 * @return string
	 */
	public static function diff($timestamp, $formats = null) 
	{
		if ($formats == null) {
			$formats = self::$_DIFF_FORMAT;
		}
		/* 计算出时间差 */
		$seconds = time() - $timestamp;
		$minutes = floor($seconds / 60);
		$hours 	 = floor($minutes / 60);
		$days 	 = floor($hours / 24);
		
		if ($days > 0) {
			$diffFormat = &#39;DAY&#39;;
		} else {
			$diffFormat = ($hours > 0) ? &#39;HOUR&#39; : &#39;MINUTE&#39;;
			if ($diffFormat == &#39;HOUR&#39;) {
				$diffFormat .= ($minutes > 0 && ($minutes - $hours * 60) > 0) ? &#39;_MINUTE&#39; : &#39;&#39;;
			} else {
				$diffFormat = (($seconds - $minutes * 60) > 0 && $minutes > 0) 
								? $diffFormat.&#39;_SECOND&#39; : &#39;SECOND&#39;;
			}
		}
		
		$dateDiff = null;
		switch ($diffFormat) {
			case &#39;DAY&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $days);
				break;
			case &#39;DAY_HOUR&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $days, $hours - $days * 60);
				break;
			case &#39;HOUR&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $hours);
				break;
			case &#39;HOUR_MINUTE&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $hours, $minutes - $hours * 60);
				break;
			case &#39;MINUTE&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $minutes);
				break;
			case &#39;MINUTE_SECOND&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $minutes, $seconds - $minutes * 60);
				break;
			case &#39;SECOND&#39;:
				$dateDiff = sprintf($formats[$diffFormat], $seconds);
				break;
		}
		return $dateDiff;
	}
}

echo DateFormat::diff(&#39;1310455823&#39;);
/* 33分钟47秒前  */

                   

                   

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn