• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

php将unix时间戳替换成易于阅读的格式

PHP 水墨上仙 3051次浏览 0个评论

将unix时间戳输出为类似于 20秒前,1天前,3个月前这样的格式

<?php
function user_friendly_date($timestamp, $echo = false, $dateFormat = 'm/d/Y H:i:s')
{
	$ufdate = '';
	$now = time();
	$elapsed = $now - $timestamp;
	if($elapsed <= 0) $ufdate = 'Now';
	else if($elapsed == 1) $ufdate = "1 Second ago";
	else if($elapsed < 60) $ufdate = "{$elapsed} Seconds ago";
	else if($elapsed < 3600) //One hour in seconds
	{
		$mins = floor($elapsed/60);
		$secs = $elapsed%60;
		$disp = min(($secs <= 30 ? $mins : $mins + 1), 59);
		$ufdate = "{$disp} Minute" . ($disp == 1 ? '' : 's') ." ago";
	}
	else if($elapsed < 86400) //One day in seconds
	{
		$hours = floor($elapsed/3600);
		$mins = floor(($elapsed%3600)/60);
		$disp = min(($mins <= 30 ? $hours : $hours + 1), 23);
		$ufdate = "{$disp} Hour" . ($disp == 1 ? '' : 's') ." ago";
	}
	else if($elapsed < 604800) //One week in seconds
	{
		$days = floor($elapsed/86400);
		$hours = floor(($elapsed%86400)/3600);
		$disp = min(($hours <= 12 ? $days : $days + 1), 6);
		$ufdate = "{$disp} Day" . ($disp == 1 ? '' : 's') ." ago";
	}
	else $ufdate = date($dateFormat, $timestamp);
	if($echo) echo $ufdate;
	return $ufdate;
}
 
//Usage
$now = time();
$tenSecsAgo = $now - 10;
$oneMinuteAgo = $now - 60;
$thirtyNineMinsAgo = $now - (39 * 60); //minutes * seconds
$elevenHoursAgo = $now - (11 * 60 * 60); //hours * minutes * seconds
$twoDaysAgo = $now - (2 * 24 * 60 * 60); //days * hours * minutes * seconds
 
echo "<p>\n";
echo user_friendly_date($tenSecsAgo), " <br>\n";
echo user_friendly_date($oneMinuteAgo), " <br>\n";
echo user_friendly_date($thirtyNineMinsAgo), " <br>\n";
echo user_friendly_date($elevenHoursAgo), " <br>\n";
echo user_friendly_date($twoDaysAgo), " <br>\n";
echo "</p>";
?>


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明php将unix时间戳替换成易于阅读的格式
喜欢 (0)

您必须 登录 才能发表评论!

加载中……