DateInterval
PHP < 5.3 はこのクラスをサポートしていないためDateTime::diff()
(これが正しい方法です) は使用できません。5.2.x で機能させるには、これを手動で行う必要があります。
計算は実際には非常に簡単です。
// Get the difference between the two dates, in seconds
$diff = $future_date->format('U') - $now->format('U');
// Calculate the days component
$d = floor($diff / 86400);
$diff %= 86400;
// Calculate the hours component
$h = floor($diff / 3600);
$diff %= 3600;
// Calculate the minutes component
$m = floor($diff / 60);
// Calculate the seconds component
$s = $diff % 60;
// $d, $h, $m and $s now contain the values you want, so you can just build a
// string from them
$str = "$d d, $h h, $m m, $s s";
ただし、うるう秒が考慮されていないため、より大きな間隔では不正確さが生じます。これは、数秒で終了する可能性があることを意味しますが、元のフォーマット文字列には秒のコンポーネントが含まれていないため、これはあなたがやっていることにとってあまり重要ではないと思います.
$now
から減算する必要があり$future_date
、その逆ではないことにも注意してください。そうしないと、結果が負になります。
動いているのを見る