2015-10-05 142 views
2

我有數據庫中的列存儲date,time and duration當前和數據庫存儲日期和時間之間的差異

<form action="exam_schedule.php" method="post"> 
    <input type="date" name="date" value=""> 
    <input type="time" name="time" value=""> 
    <input type="number" name="duration" value=""> 
    <input type="submit" name="submit" value="submit"> 
</form> 

它在數據庫中完美存儲日期,但沒有提及隨時間推移的AM和PM。 我想用存儲在數據庫中的值來計算當前日期和時間之間的差異。

$query="SELECT * from exam_schedule"; 
$result=mysqli_query($connection,$query); 
while($rows=mysqli_fetch_assoc($result)) 
{  
    $exam_date=$rows['date']; 
    $exam_time=$rows['time'];  
    echo $exam_date-date("Y-m-d"); // but it returns 0  
} 

如何計算日期和時間之間的差異

回答

2

echo $ exam_date-date(「Y-m-d」); //但它返回0

你在這裏做的是用另一個字符串減去一個字符串。

echo '2015-12-09' - '2015-10-05'; 

此印刷品0

你可能想要做的是使用像

$diff = strtotime($exam_date) - strtotime('now'); 

這東西拿到兩個日期時間之間的間隔秒。

+0

先生我怎樣才能存儲日期和時間數據庫使用輸入字段 允許我只存儲日期和允許我存儲時間。我想在同一欄中同時記錄日期和時間,然後想要計算它們之間的差異 –

+1

檢查'datetime-local':http://www.w3.org/TR/html-markup/input.datetime- local.html – Federkun

0

可能不理解你做什麼,但你應該做這樣的事情:

echo date("Y-m-d", strototime($exam_date)); 

你可以請參閱PHP的Date參考。

如果你想用時間來工作,它取決於格式,如果你的MySQL變量是這樣的:

$exam_date = '2015-10-10'; 
$exam_time = '22:53:00'; 

然後你可以用內插的日期和時間相結合:

echo date("Y-m-d H:i:s", strtotime($exam_date." ".$exam_time)); 

比較數據庫的時間與現在:

$db_date = date("Y-m-d H:i:s", strtotime($exam_date." ".$exam_time)); 
$date = date("Y-m-d H:i:s"); 

$current = $date; 
$days = 0; 
while ($current <= $db_date) { 
    $days++; 
    $current = date("Y-m-d H:i:s", strtotime("+1 day", strtotime($current))); 
} 
+0

我正在存儲考試時間表數據庫即日期2016年10月6日TIME 10實現什麼存儲在日期和時間的數據庫中。 –

+0

你的時間總是有AM/PM,但沒有秒? – mdixon18

+0

我正在使用標籤它只允許HH:MM:AM –

0

嘗試是這樣的

$currentdate = date("Y-m-d"); 
$date_from_db = date_create($exam_date); 
$diff = date_diff($date1,$date2); 
2

我建議使用日期和時間在MySQL中。我現在我要計算當前的日期和時間值之間的差異:00:你希望可以用DATEDIFF(date1, date2) & TIMEDIFF(time1, time2)

$query="SELECT e.*, DATEDIFF(CURRENT_DATE(), `date`) as date_dif, TIMEDIFF(CURRENT_TIME(), `time`) as time_dif FROM exam_schedule e"; 
$result=mysqli_query($connection,$query); 
while($rows=mysqli_fetch_assoc($result)) 
{  
    $exam_date=$rows['date']; 
    $exam_time=$rows['time'];  
    echo $rows['date_dif']; // difference in days 
    echo $rows['time_dif']; // difference in hh:mm:ss 
} 
+0

先生您的答案是非常有幫助的。它給了我我想要的結果。但如果我將日期和時間存儲在數據類型爲「datetime」的mysql列中(它將日期和時間同時存儲在同一列中,那麼我將如何計算差值b/w當前值和存儲時間)。 謝謝 –

+0

您可以使用相同的函數'TIMEDIFF()' – mynawaz

相關問題