PHP计算年龄

时间:2019-03-14
本文章向大家介绍PHP计算年龄,主要包括PHP计算年龄使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

<?php

$birthday = strtotime('1992-10-03');

$time = time();//2019-03-14;
function datediffage($birthday, $time)
{
$birthday = getDate($birthday);
$time = getDate($time);

$monthDays = array(
    1 => 31,
    2 => 28,
    3 => 31,
    4 => 30,
    5 => 31,
    6 => 30,
    7 => 31,
    8 => 31,
    9 => 30,
    10 => 31,
    11 => 30,
    12 => 31
);
$y = $m = $d = 0;
//天相减为正
if ($time['mday'] >= $birthday['mday']) { 
    //月相减为正
    if ($time['mon'] >= $birthday['mon']) {
        $y = $time['year'] - $birthday['year'];
        $m = $time['mon'] - $birthday['mon'];
    } else {
         //月相减为负,借年
        $y = $time['year'] - $birthday['year'] - 1;
        $m = $time['mon'] - $birthday['mon'] + 12;
    }
    $d = $time['mday'] - $birthday['mday'];
    return ($y == 0 ? '' : $y . '岁') . ($m == 0 ? '' : $m . '个月') . ($d == 0 || $y > 0 ? '' : $d . '天');
}
//天相减为负,借月
if ($time['mon'] == 1) { //1月,借年
    $y = $time['year'] - $birthday['year'] - 1;
    $m = $time['mon'] - $birthday['mon'] + 12;
    $d = $time['mday'] - $birthday['mday'] + $monthDays[12];
    return ($y == 0 ? '' : $y . '岁') . ($m == 0 ? '' : $m . '个月') . ($d == 0 || $y > 0 ? '' : $d . '天');
}
//3月,判断闰年取得2月天数
if ($time['mon'] == 3) { 
    $d = $time['mday'] - $birthday['mday'] + ($time['year'] % 4 == 0 ? 29 : 28);
} else {
    $d = $time['mday'] - $birthday['mday'] + $monthDays[$time['mon'] - 1];
}
//借月后,月相减为正
if ($time['mon'] >= $birthday['mon'] + 1) { 
    $y = $time['year'] - $birthday['year'];
    $m = $time['mon'] - $birthday['mon'] - 1;
} else { 
    //借月后,月相减为负,借年
    $y = $time['year'] - $birthday['year'] - 1;
    $m = $time['mon'] - $birthday['mon'] + 12 - 1;
}
return ($y == 0 ? '' : $y . '岁') . ($m == 0 ? '' : $m . '个月') . ($d == 0 || $y > 0 ? '' : $d . '天');

}
var_dump(datediffage($birthday, $time));

上一页 下一页

原文地址:http://www.manongjc.com/article/71896.html

上一篇:Pytest测试框架

下一篇:爬取股票信息