当前和数据库存储日期和时间之间的差异

时间:2015-10-05 11:44:38

标签: php mysql

我在数据库中有一列存储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    
}

如何计算日期和时间之间的差异

4 个答案:

答案 0 :(得分:3)

我建议使用日期和时间在MySQL中。您可以使用DATEDIFF(date1, date2)&amp; 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
}

答案 1 :(得分:2)

  

echo $ exam_date-date(&#34; Y-m-d&#34;); //但它返回0

这里你要做的是用另一个字符串减去一个字符串。

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

此次打印0

您可能想要做的是使用类似

的内容
$diff = strtotime($exam_date) - strtotime('now');

这得到两个日期时间之间的间隔秒。

答案 2 :(得分: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)));
}

答案 3 :(得分:0)

尝试这样的事情

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