2011-10-08 40 views
3
//Example data 
$current_time = 1318075950; 
$unbanned_time = $current_time + strtotime('+1 minute'); 


if ($unbanned_time > $current_time) { 
    $th1is = date('Y-m-d H:i:s', $unbanned_time) - date('Y-m-d H:i:s', $current_time); 
    echo date('Y-m-d H:i:s', $th1is); 

我想輸出多長時間直到用戶被解除...年,月,日,小時,分和秒......但是這給了我一些奇怪的結果..剩下多久? php + date

+0

什麼是你所得到的結果設置? – afuzzyllama

+0

1970-01-01 00:58:26 – John

回答

4

我會建議使用日期時間

$DateTime = new DateTime(); 
$unbanned_DateTime = new DateTime(); 
$unbanned_DateTime = $unbanned_DateTime->modify('+1 minute'); 

if ($unbanned_DateTime > $DateTime) { 
    $interval = $DateTime->diff($unbanned_DateTime); 
    $years = $interval->format('%y'); 
    $months = $interval->format('%m'); 
    $days = $interval->format('%d'); 
    $hours = $interval->format('%h'); 
    $minutes = $interval->format('%i'); 
    $seconds = $interval->format('%s'); 
} 

而不是使用每一個值作爲變量,你可以使用 - >格式()的一個輸出。隨你便。

記住DateTime->格式()需要一個時區在php.ini或

date_default_timezone_set('....'); 
+0

我一直在尋找更進一步的類,它看起來非常好,並處理日期,這將更容易,那麼非常感謝。 – John

5

您應該查看有關如何使用日期/時間功能的手冊。

首先,而非

$current_time + strtotime('+1 minute') 

使用

strtotime('+1 minute', $current_time); 

(參見手冊上strtotime)。

其次,date函數返回一個字符串。在大多數情況下,減去兩個字符串並不是很有用。

if ($unbanned_time > $current_time) { 
    $th1is = $unbanned_time - $current_time; 
    echo $th1is/3600 . ' hours'; 
} 

這將輸出以小時爲單位的剩餘時間,但也有許多功能,這將產生更好的格式(或者你可以編寫一個自己)。

+0

是的,我打算使用DateTime類。儘管這是一篇內容豐富的文章,並且感謝您的幫助,但沒有語法,呵呵!艱難的早晨。 – John

2

date()返回一個字符串,減去兩個字符串在這裏沒有意義。您可以使用基本的數學計算剩餘時間:

<?php 
$current_time = time(); 
$unbanned_time = /* whatever */; 
$seconds_diff = $unbanned_time - $current_time(); 
echo "You're unbanned at " . date("Y-m-d H:i:s", $unbanned_time) . " which is over "; 
if ($seconds_diff <= 120) { 
    echo "$seconds_diff seconds"; 
} else if ($seconds_diff <= 7200) { 
    echo floor($seconds_diff/60) . " minutes"; 
} else if ($seconds_diff <= 7200 * 24) { 
    echo floor($seconds_diff/3600) . " hours"; 
} else { 
    echo floor($seconds_diff/3600/24) . " days"; 
} 
?>