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

前端 未结 2 1486
孤街浪徒
孤街浪徒 2020-12-12 00:20

Suppose I have a ticket $create_time = \"2016-08-02 12:35:04\". I want to subtract the $create_time from current date and time like $current_

相关标签:
2条回答
  • 2020-12-12 00:57

    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.

    0 讨论(0)
  • 2020-12-12 01:03

    You need to progressively work through the timestamp to extract Days, Minutes & Hours. You can use something like this.

    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..";
    }
    

    Credit https://stackoverflow.com/a/20171268/1106380

    0 讨论(0)
提交回复
热议问题