服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - php中将时间差转换为字符串提示的实现代码

php中将时间差转换为字符串提示的实现代码

2019-12-10 13:09PHP教程网 PHP教程

通过传入数据库中存储的文章发表时的UNIX时间戳,来转化为例如 几分钟前,几小时前,几天前 这样的提示。

如微博 

这看起来更加人性化,好吧,上代码 

复制代码代码如下:


<?php 
class timeAgo 

static $timeagoObject; 
private $rustle; 
private $unit; 

private function __construct() 



private function __clone(){ } 
public static function getObject() 

if(! (self::$timeagoObject instanceof self) ) 
self::$timeagoObject = new timeAgo(); 

return self::$timeagoObject; 

private function count_int($unix_C) // main function 

if(! (isset($unix_C) || is_numeric($unix_C)) ) 
return 'don\'t find parameter'; 

$d = time()-$unix_C ; // $d - unix time difference value 
$d_int =(int)floor($d/60) ; // minimum unit -- minutes unix/60 

$this->unit = 0 ; // is minutes,hour or day? 

if($d_int < 60){ // minutes in one hour 3600 
$this->rustle = $d_int; 
$this->unit = 1; 

else if($d_int < 720){ //hour in one day 3600*12 
$this->rustle = floor($d_int/60); 
$this->unit = 2 ; 

else if($d_int < 7200){ //day in ten days 3600*12*10 
$this->rustle = floor($d_int/720); 
$this->unit = 3 ; 

else{ 
$this->rustle = $d ; 
$this->unit = 4 ; 


public function piece_str($C) 

$this->count_int($C); 

$u = ''; 
switch( $this->unit ) 

case 1: 
$u = 'minute'; 
break; 
case 2: 
$u = 'hour'; 
break; 
case 3: 
$u = 'day'; 
break; 
case 4: 
$u = ''; 
break; 
case 0: 
return 'sorry , get time is fail'; 

if($this->unit < 4) 

if($this->rustle > 1) 
return (string)$this->rustle.$u.'s ago'; 
else if($this->rustle == 1) 
return (string)$this->rustle.$u.'ago'; 
else 
return 'Just now'; 


/* example: $ago = timeAgo::getObject(); 
* echo $ago->piece_str($unix); 
* // 2 days ago 
*/ 

?> 

延伸 · 阅读

精彩推荐