2015-07-12 81 views
0

我有这个功能从UNIX时间戳显示TIMEAGO:PHP TIMEAGO函数计算器一样

function Timesince($original) { 
    $original = strtotime($original); 
    // array of time period chunks 
    $chunks = array(
    array(60 * 60 * 24 * 365 , 'year'), 
    array(60 * 60 * 24 * 30 , 'month'), 
    array(60 * 60 * 24 * 7, 'week'), 
    array(60 * 60 * 24 , 'day'), 
    array(60 * 60 , 'hour'), 
    array(60 , 'min'), 
    array(1 , 'sec'), 
    ); 

    $today = time(); /* Current unix time */ 
    $since = $today - $original; 

    // $j saves performing the count function each time around the loop 
    for ($i = 0, $j = count($chunks); $i < $j; $i++) { 

    $seconds = $chunks[$i][0]; 
    $name = $chunks[$i][1]; 

    // finding the biggest chunk (if the chunk fits, break) 
    if (($count = floor($since/$seconds)) != 0) { 
     break; 
    } 
    } 

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s"; 

    if ($i + 1 < $j) { 
    // now getting the second item 
    $seconds2 = $chunks[$i + 1][0]; 
    $name2 = $chunks[$i + 1][1]; 

    // add second item if its greater than 0 
    if (($count2 = floor(($since - ($seconds * $count))/$seconds2)) != 0) { 
     $print .= ($count2 == 1) ? ', 1 '.$name2 : " $count2 {$name2}s"; 
    } 
    } 
    return $print; 
} 

这为我工作。但我需要打印timeago只有3天,3天后需要显示正常日期,如:01/01/2015。在行动中,stackoverflow使用这种方法。

该怎么做?

+0

你必须看看这个http://stackoverflow.com/queue/676824/how-to-between-between-dates-using-php?rq = 1 –

回答

0

第一步:calulate差异

$date1 = new DateTime("2007-03-24"); 
$date2 = new DateTime("2009-06-26"); 
$interval = $date1->diff($date2); 
//echo "difference " . $interval->y . " years, " . $interval->m." months, //".$interval->d." days "; 

第2步:

的使用,如果条件炫耀你的约会

if($interval->d > 3 || $interval->m >0 || $interval->y >0){ 
// echo out your date in your required format 
} 

感谢SO 使用此作为一种思想和方法.. ..

+0

如果差值为1个月,那么'$ interval-> d'将返回0 – Rizier123

+0

@ Rizier123谢谢..看我的简单方法.. –