PHP get time difference in minutes [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-08 04:33:03

问题


I looked around and nothing I saw quite worked with my database layout. Basically I need to take the current time, and a predetermined event time, and see if the current time is 10 minutes prior to the event time. This is my test file, it gets the current time into a variable, then pulls the eventTime from the database table, sets the event time to a variable, subtracts the current time from the event time, and prints the difference. The problem is that I need the minutes, and it just prints the hours.

For example 11:00 - 9:15 gives me 1, where I need it to say 105 (amount of minutes), I have really looked all over, and can't find anything that wouldn't involve changing the db structure.

The database stores event time in 24h format in hours and minutes ex 13:01, and the current time is set in the same format in php using date("H:i")

Here's some test code, the include dbconnect.php is just how I'm connecting to my database.

Thanks for any help you can offer!

 <?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>";
}
?>

Thanks to Gamster Katalin and John Conde it's solved. Here's the working code:

<?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>";
}
?>

回答1:


$datetime1 = new DateTime();
$datetime2 = new DateTime($row['eventTime']);
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%i minutes');
echo $elapsed;



回答2:


Don't forget MySQL is quite powerful for such things:

SELECT CURTIME() AS currentTime, 
       eventTime, 
       TIME_FORMAT(CURTIME() - TIME(eventTime), '%h:%i' ) AS difference 
FROM events;

Or to get only the difference:

SELECT TIME_FORMAT(CURTIME() - TIME(eventTime), '%h:%i' ) AS difference 
FROM events;


来源:https://stackoverflow.com/questions/16265942/php-get-time-difference-in-minutes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!