2015-11-27 101 views
1
$start = "2015-01-01 10:00:00"; 

$end = "2015-05-05 12:06:06"; 


$x = strtotime($start); 

$y = strtotime($end); 

$z = abs($y - $x); 

$days = floor($z/(60 * 60 * 24)); 
$years = floor($z/(365 * 60 * 60 * 24)); 

$months = floor(($z - $years * 365 * 60 * 60 * 24)/(30 * 60 * 60 * 24)); 

$days = floor(($z - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24)/(60 * 60 * 24)); 

$hours = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24)/(60 * 60)); 

$minuts = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60)/60); 

$seconds = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60 - $minuts * 60)); 

輸出是:如何找到兩個日期之間的區別

4 month 4 days 1 hour 6 minute 6 seconds 

預期成果是:

4 month 4 days 2 hour 6 minute 6 seconds 
+2

看看日期時間,對象和(日期時間 - >差異()](http://php.net/manual/en/datetime.diff.php)函數..順便說一下,小時差異是正確的...如果夏季/冬季時間considderation。 – Naruto

回答

1

DateTime是PHP中的日期一個工作的好辦法:

$start = "2015-01-01 10:00:00"; 
$end = "2015-05-05 12:06:06"; 

$d1 = new DateTime($start); 
$d2 = new DateTime($end); 

$iv = $d2->diff($d1); 

echo $iv->format('%m month, %d days, %h hours, %i minutes, %s seconds'); 
+1

要操作,這是最直的但是@pavlovich可能想要編輯OP的預期輸出的答案。 4個月4天2小時6分6秒 –

+0

@MarkNg更新,謝謝 – pavlovich

+0

只是想知道,但%m月份和%m分鐘輸出相同嗎? ;) – Naruto

0

你的代碼沒有錯,你的概率巧妙地需要包括你的默認時區,就像我在非洲,所以我總是使用下面的線來設置我的時區。

date_default_timezone_set('Africa/Harare'); 

你只需要罰什麼是你的區域,然後將其分配給方法date_default_timezone_set();

0
$start_date = new DateTime('2007-09-01 04:10:58'); 
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00')); 
echo $since_start->days.' days total<br>'; 
echo $since_start->y.' years<br>'; 
echo $since_start->m.' months<br>'; 
echo $since_start->d.' days<br>'; 
echo $since_start->h.' hours<br>'; 
echo $since_start->i.' minutes<br>'; 
echo $since_start->s.' seconds<br>'; 
0

使用下面的代碼

$start = date_create('2015-01-01 10:00:00'); 
$end = date_create('2015-05-05 12:06:06'); 
$diffObj = date_diff($start, $end); 
//accesing days 
$days = $diffObj->d; 
//accesing months 
$months = $diffObj->m; 
//accesing years 
$years = $diffObj->y; 
//accesing hours 
$hours=$diffObj->h; 
//accesing minutes 
$minutes=$diffObj->i; 
//accesing seconds 
$seconds=$diffObj->s; 
echo '<center>'; 
echo '' . $days . ' day(s), ' . $months . ' month(s), ' . $years . 'year(s), '.$hours.' hour(s),'.$minutes.' minute(s), '.$seconds.' second(s) </b>'; 
echo '</center>'; 
相關問題