转换标准日期到当前时间在小时/分钟/


Convert Standard Date to Current Time in Hours/Mins/

假设我有一个生成

的日期函数

输出: 2011-10-03

PHP:

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

无论如何要得到这个日期而不是显示2 days 1 hour ago

这个函数可能有些用处。您可能需要花几个月的时间来改进检查,但这只是一个简单的示例:

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 days 16 hours 6 minutes 2 seconds ago

如果你只想要日期和小时,那么你可以选择回显这两个:

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

2 days 16 hours ago