1. 程式人生 > >php計算兩個時間相差的天數、小時數、分鐘數、秒數

php計算兩個時間相差的天數、小時數、分鐘數、秒數


$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取模,則得到相差的秒數。

原文地址:https://segmentfault.com/a/1190000016816083