由於資料庫習慣將日期存成文字格式。
所以取得的日期均為"YYYYMMDD";
如果要計算兩個日期差幾年、差幾月、差幾日...
則需要轉換格式並相減。
自訂函數: DateDiff ($stdate, $endate, $type) {
// $stdate-起始日期, $endate-終止日期, $type-日期單位
$eyear = date("Y", strtotime(substr($endate, 0, 4)."-".substr($endate, 4, 2)."-".substr($endate, 6, 2)));
$syear = date("Y", strtotime(substr($stdate, 0, 4)."-".substr($stdate, 4, 2)."-".substr($stdate, 6, 2)));
$emonth = date("m", strtotime(substr($endate, 0, 4)."-".substr($endate, 4, 2)."-".substr($endate, 6, 2)));
$smonth = date("m", strtotime(substr($stdate, 0, 4)."-".substr($stdate, 4, 2)."-".substr($stdate, 6, 2)));
$eday = date("d", strtotime(substr($endate, 0, 4)."-".substr($endate, 4, 2)."-".substr($endate, 6, 2)));
$sday = date("d", strtotime(substr($stdate, 0, 4)."-".substr($stdate, 4, 2)."-".substr($stdate, 6, 2)));
$rtnum = 0;
switch ($type) {
case 'Y': // 年數
$rtnum = $eyear - $syear;
break;
case 'm': // 月數
$rtnum = ($eyear - $syear) * 12 + $emonth - $smonth;
break;
case 'd': // 日數
$rtnum = (mktime(0, 0, 0, $emonth, $eday, $eyear) - mktime(0, 0, 0, $smonth, $sday, $syear)) / (3600 * 24);
break;
default:
$rtnum = 0;
}
return $rtnum;
所以取得的日期均為"YYYYMMDD";
如果要計算兩個日期差幾年、差幾月、差幾日...
則需要轉換格式並相減。
自訂函數: DateDiff ($stdate, $endate, $type) {
// $stdate-起始日期, $endate-終止日期, $type-日期單位
$eyear = date("Y", strtotime(substr($endate, 0, 4)."-".substr($endate, 4, 2)."-".substr($endate, 6, 2)));
$syear = date("Y", strtotime(substr($stdate, 0, 4)."-".substr($stdate, 4, 2)."-".substr($stdate, 6, 2)));
$emonth = date("m", strtotime(substr($endate, 0, 4)."-".substr($endate, 4, 2)."-".substr($endate, 6, 2)));
$smonth = date("m", strtotime(substr($stdate, 0, 4)."-".substr($stdate, 4, 2)."-".substr($stdate, 6, 2)));
$eday = date("d", strtotime(substr($endate, 0, 4)."-".substr($endate, 4, 2)."-".substr($endate, 6, 2)));
$sday = date("d", strtotime(substr($stdate, 0, 4)."-".substr($stdate, 4, 2)."-".substr($stdate, 6, 2)));
$rtnum = 0;
switch ($type) {
case 'Y': // 年數
$rtnum = $eyear - $syear;
break;
case 'm': // 月數
$rtnum = ($eyear - $syear) * 12 + $emonth - $smonth;
break;
case 'd': // 日數
$rtnum = (mktime(0, 0, 0, $emonth, $eday, $eyear) - mktime(0, 0, 0, $smonth, $sday, $syear)) / (3600 * 24);
break;
default:
$rtnum = 0;
}
return $rtnum;
留言
張貼留言