日期时间比较PHP / Mysql? [英] Datetime comparison PHP/Mysql?

查看:134
本文介绍了日期时间比较PHP / Mysql?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果(datetime - 系统日期> 15分钟)(false)



$ b

我有一个问题,
$ b

if(datetime - 系统日期< = 15分钟)(true)



但是我完全失去了。我不知道如何在PHP中进行操作。



我问我是否可以从我的数据库中选择该日期时间,并检查该datetime是否在最近15分钟之间的我的服务器,我的DB是Mysql。



希望你明白我!谢谢!






最后我感谢Sammitch和其他人,在这里我留下了片段:

  $ now = time(); 
$ target = strtotime($ row [1]);
$ diff = $ now - $ target;

// 15 minuts 15 * 60 = 900
if($ diff <= 900){
$ seconds = $ diff;
} else {
$ seconds = $ diff;
}


解决方案

如果您的日期已经在MySQL您将要在查询中进行比较,因为:


  1. MySQL具有正确的DATE类型。

  2. MySQL具有比较的索引。

  3. MySQL比PHP执行比较

  4. 在查询中较少,或者没有时间将多余的数据传回应用程序。

以下是最有效的形式。如果日期列上有一个索引,它将被使用。

  SELECT * 
FROM table
WHERE date> DATE_SUB(NOW(),INTERVAL 15 MINUTE)

文件: DATE_SUB()



如果您需要在PHP中执行此操作:

  $ now =时间(); 
$ target = strtotime($ date_from_db);
$ diff = $ now - $ target;
if($ diff> 900){
// something
}

或更简洁:

  if(time() -  strtotime($ date_from_db)> 900){
// something
}


I have one problem, im trying to make something like that:

if (datetime - system date > 15 minutes) (false)

if (datetime - system date <= 15 minutes) (true)

But im totally lost. I don't know how to make the operation in PHP.

Im asking if i can pick that datetime from my database and check if that datetime is between the last 15 minutes of my server, my DB is Mysql.

Hope you understand me! Thanks!


Finally i make it thanks to Sammitch and the other ones, here i leave the snippet:

    $now = time();
     $target = strtotime($row[1]);
     $diff = $now - $target;

    //15 minuts 15*60 = 900
     if ($diff <= 900) {
        $seconds =  $diff;
     } else {
$seconds =  $diff;    
 }

解决方案

If your dates are already in MySQL you will want to do the comparison in the query because:

  1. MySQL has proper DATE types.
  2. MySQL has indexes for comparison.
  3. MySQL performs comparisons much faster than PHP.
  4. If you filter your data in the query then less, or no time is spent transferring superfluous data back to the application.

Below is the most efficient form. If there is an index on the date column it will be used.

SELECT *
FROM table
WHERE date > DATE_SUB(NOW(), INTERVAL 15 MINUTE)

Docs: DATE_SUB()

If you need to do it in PHP:

$now = time();
$target = strtotime($date_from_db);
$diff = $now - $target;
if ( $diff > 900 ) {
  // something
}

or, more succinctly:

if( time() - strtotime($date_from_db) > 900 ) {
  // something
}

这篇关于日期时间比较PHP / Mysql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆