【发布时间】:2013-04-28 17:59:47
【问题描述】:
我环顾四周,没有看到与我的数据库布局非常匹配的东西。基本上我需要获取当前时间和预定的事件时间,并查看当前时间是否比事件时间早 10 分钟。这是我的测试文件,它将当前时间放入一个变量中,然后从数据库表中提取事件时间,将事件时间设置为一个变量,从事件时间中减去当前时间,然后打印差值。问题是我需要分钟,它只打印小时。
例如 11:00 - 9:15 给了我 1,我需要它说 105(分钟数),我真的看了一遍,找不到任何不涉及更改数据库的东西结构。
数据库以 24 小时格式存储事件时间,以小时和分钟为单位,例如 13:01,并且当前时间在 php 中使用 date("H:i") 以相同的格式设置
这是一些测试代码,包含 dbconnect.php 就是我连接数据库的方式。
感谢您提供的任何帮助!
<?php
include 'dbconnect.php';
$the_time = date('H:i');
echo $the_time." </br></br>";
$sql="SELECT eventTime FROM events";
$result=$conn->query($sql);
while ($row = $result->fetch_assoc()) {
$new_time=$row['eventTime'];
echo $new_time."New Time</br>";
echo $the_time-$new_time."The Difference</br></br>";
}
?>
感谢 Gamster Katalin 和 John Conde,问题解决了。这是工作代码:
<?php
include 'dbconnect.php';
date_default_timezone_set('America/New_York');
$the_time = date('H:i');
echo $the_time." </br></br>";
$sql="SELECT eventTime FROM events";
$result=$conn->query($sql);
while ($row = $result->fetch_assoc()) {
$new_time=$row['eventTime'];
echo $new_time."New Time</br>";
$datetime1 = new DateTime($the_time);
$datetime2 = new DateTime($new_time);
$interval = $datetime1->diff($datetime2);
$hours=$interval->format('%h');
$minutes= $interval->format('%i');
echo $hours." The Difference in Hours</br>".$minutes." The Difference in Minutes</br></br>";
}
?>
【问题讨论】:
-
使用 PHP DateTime::sub 然后 DateTime::format
-
也许我误解了一些东西,但我的时间格式似乎不允许我这样做,我如何将存储在数据库中的时间作为 varchar 转换成一些东西(据我所知,自 1970 年以来的秒数)我可以使用这些功能吗?
-
将 DateTime::setTime 与您的值一起使用。如果您想要当前时间,只需
new DateTime('now')。之后,您可以使用 DateTime::format 将其转换回您的格式。 -
谢谢!在你和约翰康德之间,你们向我展示了我完全误解了间隔是如何工作的,我将在有效的代码中进行编辑!