[英]Mysql date difference between current date and date stored in database
[英]difference between current and database stored date and time
我在數據庫中存儲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
}
我如何計算日期和時間之間的時差
我建議在MySQL中使用日期和時間。 您可以使用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
}
echo $ exam_date-date(“ Ymd”); //但返回0
您在這里要做的是用另一個字符串減去一個字符串。
echo '2015-12-09' - '2015-10-05';
此打印0
。
您可能想要做的是使用類似
$diff = strtotime($exam_date) - strtotime('now');
這將獲得兩個日期時間之間的間隔秒數。
可能不了解您該做什么,但您應該這樣做:
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)));
}
試試這個
$currentdate = date("Y-m-d");
$date_from_db = date_create($exam_date);
$diff = date_diff($date1,$date2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.