转换标准日期为当前时间以小时/分钟]/
问题描述:
说我有一个产生日期函数转换标准日期为当前时间以小时/分钟]/
输出: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