核心代碼:
Class Utils { /** * format MySQL DateTime (YYYY-MM-DD hh:mm:ss) 把mysql中查找出來的數據格式轉換成時間秒數 * @param string $datetime */ public function fmDatetime($datetime) { $year = substr($datetime,0,4); $month = substr($datetime,5,2); $day = substr($datetime,8,2); $hour = substr($datetime,11,2); $min = substr($datetime,14,2); $sec = substr($datetime,17,2); return mktime($hour,$min,$sec,$month,$day,0+$year); } /** * * 根據倆個時間獲取倆個時間的 包含的 年,月數,天數,小時,分鐘,秒 * @param String $start * @param String $end * @return ArrayObject */ private function diffDateTime($DateStart,$DateEnd){ $rs = array(); $sYear = substr($DateStart,0,4); $eYear = substr($DateEnd,0,4); $sMonth = substr($DateStart,5,2); $eMonth = substr($DateEnd,5,2); $sDay = substr($DateStart,8,2); $eDay = substr($DateEnd,8,2); $startTime = $this->fmDatetime($DateStart); $endTime = $this->fmDatetime($DateEnd); $dis = $endTime-$startTime;//得到倆個時間的秒數 $d = ceil($dis/(24*60*60));//得到天數 $rs['day'] = $d;//天數 $rs['hour'] = ceil($dis/(60*60));//小時 $rs['minute'] = ceil($dis/60);//分鐘 $rs['second'] = $dis;//秒數 $rs['week'] = ceil($d/7);//周 $tem = ($eYear-$sYear)*12;//月份 $tem1 = $eYear-$sYear;//年 if($eMonth-$sMonth<0){//月份相減為負 $tem +=($eMonth-$sMonth); }else if($eMonth==$sMonth){//月份相同 if($eDay-$sDay>=0){ $tem ++; $tem1++; } }else if($eMonth-$sMonth>0){//月份相減正負 $tem1++; if($eDay-$sDay>=0){//且日期相減為正數 $tem +=($eMonth-$sMonth)+1; }else{ $tem +=($eMonth-$sMonth); } } $rs['month'] = $tem; $rs['year'] = $tem1; return $rs; } }
一年多一天,返回的是2年,一個月多一天返回的是2個月,以此推......項目需要,才做此出來,開始我也到網上找這樣的例子,但大家都是把年就按365天來算,月就按30天來算,這樣算出來的結果肯定是沒用的,年有可能是366天,月有可能是31,29,28都有可能