php 如何在php/mysql中比较日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16538026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:19:34  来源:igfitidea点击:

how to compare date and time in php/ mysql

phpmysql

提问by Princewill Obinna Iwuorie

i need to compare date and time in php/mysql basically i have an application and a server the application needs to connect to the server to check new entries into the database. the server receives the datetime as a string from the application which is done here

我需要在 php/mysql 中比较日期和时间,基本上我有一个应用程序和一个服务器,该应用程序需要连接到服务器以检查数据库中的新条目。服务器从此处完成的应用程序接收日期时间作为字符串

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss");
Calendar cal = Calendar.getInstance();
String time = dateformat.format(cal.getTime()); 

the server receives the data here

服务器在这里接收数据

f (isset($_GET["time"]) || isset($_GET["user_id"])) {
$time = $_GET['time'];
$u_id = $_GET['user_id'];
$timestr=date('y-m-d H:i:s',strtotime($time));

$result = mysql_query("SELECT MAX(created_at)from room");
$Max_time = mysql_result($result, $row);
$dbMax_time = date('y-m-d H:i:s',strtotime($Max_time));

and the comparison needs to be done here

并且需要在这里进行比较

if ($dbMax_time> $timestr) {
    $NewRooms = mysql_query("SELECT * From room WHERE created_at> CAST($timestr AS TIME)");
}

how do i go about this am confused on how to compare please help me to FIX it.

我该如何解决这个问题,我对如何比较感到困惑,请帮助我修复它。

回答by Smar

Just comparing two timestamps would suffice:

只需比较两个时间戳就足够了:

$t1 = strtotime($time);
$t2 = strtotime($Max_Time);

if($t1 > $t2) { .. }

回答by Benz

Why don't you create two DateTime objects and compare these?

为什么不创建两个 DateTime 对象并比较它们?

Like:

喜欢:

$A = new DateTime(); 
$A->setTimestamp(strtotime($time));

$B = new DateTime(); 
$B->setTimestamp(strtotime($Max_Time)); 

if ($A > $B) echo "You use if statements to compare"