$startdate="2011-3-15 11:50:00";//開始時間
$enddate="2012-12-12 12:12:12";//結束時間
$date=floor((strtotime($enddate)-strtotime($startdate))/86400);
echo "相差天數:".$date."天<br><br>";
$hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);
echo "相差小時數:".$hour."小時<br><br>";
$minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
echo"相差分鍾數:".$minute."分鍾<br><br>";
$second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);
echo"相差秒數:".$second."秒";
不管是自己使用字符串來構造的時間類型(使用strtotime轉換而來的)也好,還是直接使用系統的time函數得到的時間類型也好,最終其實都是長整形的一個變量。兩個這樣的變量,就很明顯可以做減法了。
做減法得到值是相差的秒數,這個秒數對86400(一天的秒數)取余,則得到相差數。如果對86400取模,還對3600秒、60秒取余,則得到相關的小時和分鍾數。如果對86400取模,再對60取模,則得到相差的秒數。
