2013-07-12 52 views
-5

使用DateTime::createFromFormat如何計算$dt1$dt2之間的差值(分鐘)與$dt2之間的差值?如何使用DateTime :: createFromFormat計算PHP到日期/時間的分鐘數?

我試過$dt2 - $dt1,但當然產生了error

<?php 
date_default_timezone_set('America/New_York'); 

// $time1 will always be in HH:MM:SS MM/DD/YYYY format. 
$time1 = "08:18:00 07/11/2013"; 

// $time2 will always be in MM/DD/YYYY HH:MM:SS format. 
$time2 = "7/11/2013 9:11:00 AM"; 

$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1); 
$dt2 = DateTime::createFromFormat("m/d/Y g:i:s a", $time2); 
var_dump($dt1); 
var_dump($dt2); 
if ($dt1 < $dt2) echo "The first is earlier" . "\n"; 

?> 
+3

/manual/en/datetime.diff.php)方法 –

+4

這個問題似乎是無關緊要的,因爲它可能已通過閱讀[DateTime](http://PHP.net/DateTime)手冊得到解答。 – vascowhite

回答

2
$time1 = "08:18:00 07/11/2013"; 
$time2 = "7/11/2013 9:11:00 AM"; 
$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1); 
$dt2 = DateTime::createFromFormat("m/d/Y g:i:s a", $time2); 
$interval = $dt1->diff($dt2); 
echo $interval->format("%i")." minutes"; 
0

看一看DateTime::diff()

DateTime::diff - DateTimeImmutable::diff - DateTimeInterface::diff - date_diff - 返回的差之間也許使用[DIFF()](http://www.php.net 2 datetime對象