从当前日期和时间中减去一些日期和时间,就可以在PHP中找到年龄



假设我有一个票证$create_time = "2016-08-02 12:35:04"。我想像$current_time="2016-08-02 16:16:02"一样从当前日期和时间中减去$create_time,以找到格式为3hr 41min的年龄。

<?php
$sql = "SELECT count(*) as total, create_time FROM article where ticket_id='$ticket_id'";
$otrs_db = $this->load->database('otrs',true);
$result = $otrs_db->query($sql);
foreach($result->result() as $row)
{?>
    <div class="pull-left">
        <h4><b><?php echo $row->total ;?> Article(s)</b></h4>
    </div>
    <div class="pull-right">
        <h4>Age: <?php echo date("Y-m-d H:i", strtotime("-$row->create_time",strtotime($thestime))) ?>Created: <?php echo $row->create_time; ?></h4>
    </div>
<?php
}
?>

我知道我的日期减法代码是错误的。我该怎么做才对?

您应该使用DateTime类。

$create_time = "2016-08-02 12:35:04";
$current_time="2016-08-02 16:16:02";
$dtCurrent = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
$dtCreate = DateTime::createFromFormat('Y-m-d H:i:s', $create_time);
$diff = $dtCurrent->diff($dtCreate);
echo $diff->format("%Y-%m-%d %H:%i");

这将返回00-0-0 03:40有关更多格式设置的详细信息,请参阅DateInterval::format

您需要逐步通过时间戳提取Days,Minutes&小时。你可以用这样的东西。

function timeSince($t)
{
    $timeSince = time() - $t;
    $pars = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    $result = '';
    $counter = 1;
    foreach ($pars as $unit => $text) {
        if ($timeSince < $unit) continue;
        if ($counter > 2) break;
        $numberOfUnits = floor($timeSince / $unit);
        $result .= "$numberOfUnits $text ";
        $timeSince -= $numberOfUnits * $unit;
        ++$counter;
    }
    return "{$result} ago..";
}

信用https://stackoverflow.com/a/20171268/1106380

相关内容

  • 没有找到相关文章

最新更新