php 計算兩個日期的間隔天數
阿新 • • 發佈:2019-02-18
使用php內部自帶函式實現
上程式碼:
<?php
$start = "2016-05-25";
$end = "2016-05-23";
$datetime_start = new DateTime($start);
$datetime_end = new DateTime($end);
var_dump($datetime_start->diff($datetime_end));
*結果*
由結果我們知道,想要得出時間差,可以用下面方法實現object(DateInterval)[3] public 'y' => int 0 public 'm' => int 0 public 'd' => int 2 public 'h' => int 0 public 'i' => int 0 public 's' => int 0 public 'weekday' => int 0 public 'weekday_behavior' => int 0 public 'first_last_day_of' => int 0 public 'invert' => int 1 public 'days' => int 2 public 'special_type' => int 0 public 'special_amount' => int 0 public 'have_weekday_relative' => int 0 public 'have_special_relative' => int 0
$start = "2016-05-25";
$end = "2016-05-23";
$datetime_start = new DateTime($start);
$datetime_end = new DateTime($end);
$days = $datetime_start->diff($datetime_end)->days;
echo "時間差是:$days";
*最終結果為*
時間差是:2
2.date_create()、date_diff()實現
*列印結果*$start = "2016-05-25"; $end = "2016-05-23"; $datetime_start = date_create($start); $datetime_end = date_create($end); $days = date_diff($datetime_start, $datetime_end); var_dump($days);
object(DateInterval)[3] public 'y' => int 0 public 'm' => int 0 public 'd' => int 2 public 'h' => int 0 public 'i' => int 0 public 's' => int 0 public 'weekday' => int 0 public 'weekday_behavior' => int 0 public 'first_last_day_of' => int 0 public 'invert' => int 1 public 'days' => int 2 public 'special_type' => int 0 public 'special_amount' => int 0 public 'have_weekday_relative' => int 0 public 'have_special_relative' => int 0
具體實現:
$start = "2016-05-25";
$end = "2016-05-23";
$datetime_start = date_create($start);
$datetime_end = date_create($end);
$days = date_diff($datetime_start, $datetime_end)->days;
echo "時間間隔是:$days";
*結果*
時間間隔是:2
推薦閱讀:PHP 計算日期間隔天數