2015-10-05 144 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

相关问题