PHP calculates the number of years, months and days between two dates

WBOY
Release: 2016-07-29 09:09:16
Original
2216 people have browsed it

The first method is implemented using PHP class library

<code>/**
 * function:计算两个日期相隔多少年,多少月,多少天
 * param string $date1[格式如:2011-11-5]
 * param string $date2[格式如:2012-12-01]
 * return array array('年','月','日');
 */
function diffDate($date1,$date2)
{
    $datetime1 = new \DateTime($date1);
    $datetime2 = new \DateTime($date2);
    $interval = $datetime1->diff($datetime2);
    $time['y']         = $interval->format('%Y');
    $time['m']         = $interval->format('%m');
    $time['d']         = $interval->format('%d');
    $time['h']         = $interval->format('%H');
    $time['i']         = $interval->format('%i');
    $time['s']         = $interval->format('%s');
    $time['a']         = $interval->format('%a');    // 两个时间相差总天数
    return $time;
}


# 使用实例
$sss = diffDate('2015-12-25 12:30:30', '2015-12-26 15:00:00');
print_r($sss);

# 输出
Array
(
    [y] => 00
    [m] => 0
    [d] => 1
    [h] => 02
    [i] => 29
    [s] => 30
    [a] => 1
)</code>
Copy after login

The second method is implemented using functions (still under testing...)

<code>// 计算两个时间相差(时分秒)
$aaa = strtotime('2015-12-26 16:33:33');
$bbb = $aaa-time();
echo gmstrftime('%Y %m %d %H:%M:%S',$aaa);
exit;

$left_time = 86400 - time()+strtotime($orderInfo['create_time']);
echo:gmstrftime('%H:%M:%S',$left_time);</code>
Copy after login

The above introduces PHP to calculate the number of years, months, and days between two dates, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!