PHP计算时间日期差并检验日期格式是否正确(月龄计算)

/**
 * 校验日期格式是否正确
 * 
 * @param string $date 日期
 * @param string $formats 需要检验的格式数组
 * @return boolean
 */
function checkDateIsValid($date, $formats = array("Ymd","Y-m-d", "Y/m/d")) {
    $unixTime = strtotime($date);
    if (!$unixTime) { //strtotime转换不对,日期格式显然不对。
        return false;
    }
    //校验日期的有效性,只要满足其中一个格式就OK
    foreach ($formats as $format) {
        if (date($format, $unixTime) == $date) {
            return true;
        }
    }
    return false;
}
/**
 * 计算日期时间差
 * 
 * @param string $date_befor 日期1
 * @param string $date_after 日期2
 * @param string $diff_type 返回类型 YMDHIS
 * @return boolean | int 相差结果 失败返回false
 */
function calcDateDiff($date_befor,$date_after,$diff_type = 'm'){
    if( checkDateIsValid($date_befor) && checkDateIsValid($date_after) ){
        $date_befor = strtotime($date_befor);
        $date_after = strtotime($date_after);
        switch(strtoupper($diff_type)){
            case 'Y':
                $c['B']['Y'] = date('Y',$date_befor);
                $c['B']['M'] = date('m',$date_befor);
                $c['B']['D'] = date('d',$date_befor);
                $c['A']['Y'] = date('Y',$date_after);
                $c['A']['M'] = date('m',$date_after);
                $c['A']['D'] = date('d',$date_after);
                $c['C']['Y'] = ($c['A']['Y'] - $c['B']['Y']) * 12;
                $c['C']['M'] = ($c['A']['M'] - $c['B']['M']) * 1;
                $c['C']['D'] = ($c['A']['D'] - $c['B']['D']) >= 0 ? 0 : -1 ;
                return floor(($c['C']['Y'] + $c['C']['M'] + $c['C']['D'] )/12) ;
                break;
            case 'M':
                $c['B']['Y'] = date('Y',$date_befor);
                $c['B']['M'] = date('m',$date_befor);
                $c['B']['D'] = date('d',$date_befor);
                $c['A']['Y'] = date('Y',$date_after);
                $c['A']['M'] = date('m',$date_after);
                $c['A']['D'] = date('d',$date_after);
                $c['C']['Y'] = ($c['A']['Y'] - $c['B']['Y']) * 12;
                $c['C']['M'] = ($c['A']['M'] - $c['B']['M']) * 1;
                $c['C']['D'] = ($c['A']['D'] - $c['B']['D']) >= 0 ? 0 : -1 ;
                return $c['C']['Y'] + $c['C']['M'] + $c['C']['D'] ;
                break;
            case 'D':
                return floor(($date_after - $date_befor)/86400);
                break;
            case 'H':
                return floor(($date_after - $date_befor)/3600);
                break;
            case 'I':
                return floor(($date_after - $date_befor)/60);
                break;
            case 'S':
                return $date_after - $date_befor;
                break;
            default:
                return $date_after - $date_befor;
                break;
        }
        return true;
    }
    return false;
}
Last modification:March 13th, 2018 at 01:30 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment