【问题标题】:Subtract some date and time from current date and time to find age in PHP从当前日期和时间中减去一些日期和时间以在 PHP 中查找年龄
【发布时间】:2016-12-07 16:09:58
【问题描述】:

假设我有一张票 $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
}
?>

我知道我的日期减法代码是错误的。我怎样才能做到正确?

【问题讨论】:

  • 试试date("Y-m-d H:i", time() - strtotime($row-&gt;create_time))
  • 我确定这是一个重复的问题,但您应该使用 date_diff()
  • @FrankerZ 你的代码不起作用

标签: php mysql date datetime


【解决方案1】:

您应该使用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 了解更多格式详细信息。

【讨论】:

【解决方案2】:

您需要逐步处理时间戳以提取天、分和小时。你可以使用这样的东西。

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

【讨论】:

  • 与 PHP 5.2.0 中引入的 DateTime 类相比,这是非常难看的代码。请使用DateTime.
猜你喜欢
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
相关资源
最近更新 更多