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

php时间友好格式化

PHP中文网
Release: 2016-05-25 17:13:42
Original
1282 people have browsed it

[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秒前  */
Copy after login

                   

                   

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template