說我有一個產生日期函數轉換標準日期爲當前時間以小時/分鐘]/
輸出:2011-10-03
PHP:
$todayDt = date('Y-m-d');
反正拿到這個日期改爲顯示2 days 1 hour ago
說我有一個產生日期函數轉換標準日期爲當前時間以小時/分鐘]/
輸出:2011-10-03
PHP:
$todayDt = date('Y-m-d');
反正拿到這個日期改爲顯示2 days 1 hour ago
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
這個職位僅僅是,做一個解決方案不使用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小時以前
date_diff http://nz.php.net/manual/en/function.date-diff.php – 2011-10-05 19:51:06
您可以使用[日期時間:: DIFF](HTTP:// PHP。 net/manual/datetime.diff.php)和[DateInterval](php.net/manual/class.dateinterval.php)。 – ComFreek
希望能夠使用我的代碼的例子 – CodeTalk