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

时间:2016-08-02 10:37:58

标签: php mysql date datetime

假设我有一张票$create_time = "2016-08-02 12:35:04"。我想从$create_time的当前日期和时间中减去$current_time="2016-08-02 16:16:02",以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
}
?>

我知道我的日期减法代码是错误的。我该怎么办呢?

2 个答案:

答案 0 :(得分:2)

您应该使用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

答案 1 :(得分:0)

您需要逐步完成时间戳,以提取日期,分钟和时间。小时。你可以使用这样的东西。

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