2011-10-05 152 views
1

说我有一个产生日期函数转换标准日期为当前时间以小时/分钟]/

输出:2011-10-03

PHP:

$todayDt = date('Y-m-d'); 

反正拿到这个日期改为显示2 days 1 hour ago

+0

date_diff http://nz.php.net/manual/en/function.date-diff.php – 2011-10-05 19:51:06

+0

您可以使用[日期时间:: DIFF](HTTP:// PHP。 net/manual/datetime.diff.php)和[DateInterval](php.net/manual/class.dateinterval.php)。 – ComFreek

+0

希望能够使用我的代码的例子 – CodeTalk

回答

2

Th功能可能有些用处。您可能要细化月检查了一下,不过这只是一个简单的例子:

function RelativeTime($iTimestamp, $iLevel = 2) 
{ 
    !ctype_digit($iTimestamp) 
     && $iTimestamp = strtotime($iTimestamp); 

    $iSecondsInADay = 86400; 
    $aDisplay = array(); 

    // Start at the largest denominator 
    $iDiff = time() - $iTimestamp; 
    $aPeriods = array(
     array('Period' => $iSecondsInADay * 356, 'Label' => 'year'), 
     array('Period' => $iSecondsInADay * 31, 'Label' => 'month'), 
     array('Period' => $iSecondsInADay,   'Label' => 'day'), 
     array('Period' => 3600,     'Label' => 'hour'), 
     array('Period' => 60,      'Label' => 'minute'), 
     array('Period' => 1,      'Label' => 'second'), 
    ); 

    foreach ($aPeriods as $aPeriod) 
    { 
     $iCount = floor($iDiff/$aPeriod['Period']); 
     if ($iCount > 0) 
     { 
      $aDisplay[] = $iCount . ' ' . $aPeriod['Label'] . ($iCount > 1 ? 's' : ''); 
      $iDiff -= $iCount * $aPeriod['Period']; 
     } 
    } 

    $iRange = count($aDisplay) > $iLevel 
       ? $iLevel 
       : count($aDisplay); 
    return implode(' ', array_slice($aDisplay, 0, $iRange)) . ' ago'; 
} 

和用法的一些例子:

echo RelativeTime(time() - 102, 1); 
// Will output: 1 minute ago 

echo RelativeTime(time() - 2002); 
// Will output: 33 minutes 22 seconds ago 

echo RelativeTime(time() - 100002002, 6); 
// Will output: 3 years 2 months 27 days 10 hours 20 minutes 2 seconds ago 

echo RelativeTime('2011-09-05'); 
// Will output: 30 days 22 hours ago 
+0

谢谢!你能解释一下什么echo'RelativeTime(time() - 100002002,6);'Relative – CodeTalk

+0

'RelativeTime(time() - 100002002,6);'采用指定的时间戳(现在是 - 100002002秒)并构建标签。 6指定所需的详细程度(细节的6个等级意味着你从最大日期单位开始,6个细节级别:年,月,日,小时,分钟,秒如果你只指定了2个,只会得到Year,Month)。 – Tom

+0

时间差较小,比如time() - 102秒,你只能得到分秒。如果您指定1的细节级别,那么您只能获得分钟数。 – Tom

1

这个职位仅仅是,做一个解决方案不使用DateTime::diff方法。它也使用更高精度的输入,因此请注意这一点。

$now = date('Y-m-d H:i:s'); 
$then = '2011-10-03 00:00:00'; // This will calculate the difference 
           // between now and midnight October 3rd 
$nowTime = strtotime($now); 
$thenTime = strtotime($then); 

$diff = $nowTime - $thenTime; 

$secs = $diff % 60; 
$diff = intval($diff/60); 
$minutes = $diff % 60; 
$diff = intval($diff/60); 
$hours = $diff % 24; 
$diff = intval($diff/24); 
$days = $diff; 


echo($days . ' days ' . $hours . ' hours ' . $minutes . ' minutes ' . $secs . ' seconds ago'); 

在我测试了它的那一刻,产量为:

2天16小时6分钟2秒前

如果你想要的是日期和时间,然后你可以选择回显这两个:

echo($days . ' days ' . $hours . ' hours ago'); 

2天17小时以前

相关问题