2011年6月13日 星期一

PHP Function:計算(日、月、年)數差距

藉由給定的時間算出時間的差距

例子一:給定起始時間,算出差幾天
例子二:給定起始時間,算出差幾個月
例子三:給定起始時間,算出差幾年



//例子一
function dateDiff($startDate, $endDate) {
    $startArry = getdate(strtotime($startDate));
    $endArry = getdate(strtotime($endDate));
    $start_date = gregoriantojd($startArry["mon"], $startArry["mday"], $startArry["year"]);
    $end_date = gregoriantojd($endArry["mon"], $endArry["mday"], $endArry["year"]);
    return round(($end_date - $start_date), 0);
}

//例子二
function monDiff($startDate, $endDate) {
    $startyear = date("Y", strtotime($startDate));
    $endyear = date("Y", strtotime($endDate));
    $startArry = date("m", strtotime($startDate));
    $endArry = date("m", strtotime($endDate));
    return round(($endyear - $startyear), 0) * 12 + round(($endArry - $startArry), 0);
}

//例子三
function yearDiff($startDate, $endDate) {
    $startyear = date("Y", strtotime($startDate));
    $endyear = date("Y", strtotime($endDate));
    return round(($endyear - $startyear), 0);
}
//時間帶入function
echo "2011-05-03到2011-05-10 差" . dateDiff('2011-05-03', '2011-05-10') . '天<BR>';
echo "2011-1-03到2011-05-10 差" . monDiff('2011-1-03', '2011-05-10') . '月<BR>';
echo "2009-1-03到2011-05-10 差" . yearDiff('2009-1-03', '2011-05-10') . '年<BR>';

沒有留言: