2017-01-10 180 views
0

我有兩個日期是在格式Y-m-d如何獲得兩個日期之間的差異與時序

$dateOld = new DateTime("2017-01-10"); 
$dateNew = new DateTime("2017-01-11"); 

echo $diff = $dateNew->diff($dateOld)->format("%a"); 

這是工作完美的,給我確切的天了。

但現在我已經加入time,它是在H-M格式

23:3817:21現在無法理解得到之間的差的兩個dateTime

$dateOld = new DateTime("2017-01-10 23:38"); 
$dateNew = new DateTime("2017-01-11 17:21"); 

echo $diff = $dateNew->diff($dateOld)->format("%a"); 

我想即使差如果在浮點數值。現在要處理與時間串聯的日期?

+0

的可能的複製[?如何計算使用PHP的兩個日期之間的差異(http://stackoverflow.com/questions/676824/how-to-calculate-the-兩個差 - 間 - 日期,使用的PHP) – vascowhite

回答

1

使用此:

<?php 
$dateOld = new DateTime("2017-01-10 23:38"); 
$dateNew = new DateTime("2017-01-11 17:21"); 

$diff = $dateNew->diff($dateOld); 
$days = $diff->d; 
$hours = $diff->h; 
$minutes = $diff->i; 

$total_difference = $days + ($hours * 60 + $minutes)/1440; 

echo $total_difference; 

或者,沒有DateInterval:

$dateOld = new DateTime("2017-01-10 23:38"); 
$dateNew = new DateTime("2017-01-12 17:21"); 

$difference_in_seconds = $dateNew->getTimestamp() - $dateOld->getTimestamp(); 

$total_difference_in_days = $difference_in_seconds/86400; 

echo $total_difference_in_days; 

使用 - >格式( 「%A」)會給你四捨五入天。

http://php.net/manual/en/datetime.diff.php

0
$dateNew = '2017-01-11 17:21'; 
$dateOld = '2017-01-10 23:38'; 


$dateNew = new DateTime($dateNew); 
$dateOld = new DateTime($dateOld); 

$diff = $dateNew->diff($dateOld); 

echo $diff->format("%H:%I"); 

來源:http://php.net/manual/en/datetime.diff.php