Sujan Shrestha Sujan Shrestha - 5 months ago 12
MySQL Question

Subtract some date and time from current date and time to find age in PHP

Suppose I have a ticket

$create_time = "2016-08-02 12:35:04"
. I want to subtract the
from current date and time like
$current_time="2016-08-02 16:16:02"
to find the age in the format
3hr 41min


$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 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>


I know my date subtraction code is wrong. How can i do it right?


You should use DateTime class.

$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");

This returns 00-0-0 03:40 See DateInterval::format for more formatting details.