前端傳倆個標(biāo)準(zhǔn)的 時間格式過來,格式像2009-05-12 12:12:30,然后根據(jù)需要返回這個時間段的不同單位的表示,對于時間格式的校驗我這里代碼沒貼出來,所以用的時候自己考慮加上
核心代碼:
Class Utils {
/**
* format MySQL DateTime (YYYY-MM-DD hh:mm:ss) 把mysql中查找出來的數(shù)據(jù)格式轉(zhuǎn)換成時間秒數(shù)
* @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);
}
/**
*
* 根據(jù)倆個時間獲取倆個時間的 包含的 年,月數(shù),天數(shù),小時,分鐘,秒
* @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;//得到倆個時間的秒數(shù)
$d = ceil($dis/(24*60*60));//得到天數(shù)
$rs['day'] = $d;//天數(shù)
$rs['hour'] = ceil($dis/(60*60));//小時
$rs['minute'] = ceil($dis/60);//分鐘
$rs['second'] = $dis;//秒數(shù)
$rs['week'] = ceil($d/7);//周
$tem = ($eYear-$sYear)*12;//月份
$tem1 = $eYear-$sYear;//年
if($eMonth-$sMonth<0){//月份相減為負(fù)
$tem +=($eMonth-$sMonth);
}else if($eMonth==$sMonth){//月份相同
if($eDay-$sDay>=0){
$tem ++;
$tem1++;
}
}else if($eMonth-$sMonth>0){//月份相減正負(fù)
$tem1++;
if($eDay-$sDay>=0){//且日期相減為正數(shù)
$tem +=($eMonth-$sMonth)+1;
}else{
$tem +=($eMonth-$sMonth);
}
}
$rs['month'] = $tem;
$rs['year'] = $tem1;
return $rs;
}
}
一年多一天,返回的是2年,一個月多一天返回的是2個月,以此推......項目需要,才做此出來,開始我也到網(wǎng)上找這樣的例子,但大家都是把年就按365天來算,月就按30天來算,這樣算出來的結(jié)果肯定是沒用的,年有可能是366天,月有可能是31,29,28都有可能