从php now()检查mySql datetime是否早于1天

从php now()检查mySql datetime是否早于1天,php,mysql,datetime,Php,Mysql,Datetime,我有一个从MySQL返回的记录,它有一个datetime字段。我想做的是取这个值,看看它是否比24小时旧,我假设使用PHP的时间来获取当前时间 现在,如果我把它们重复出来,我会得到: 1276954824 this is php's time() 2010-06-19 09:39:23 this is the MySQL datetime 我猜最上面的是unix时间?一直在玩弄strotime,但没有取得多大成功 欢迎任何帮助 为什么要混合使用PHP时代和MySQ

我有一个从MySQL返回的记录,它有一个datetime字段。我想做的是取这个值,看看它是否比24小时旧,我假设使用PHP的时间来获取当前时间

现在,如果我把它们重复出来,我会得到:

 1276954824            this is php's time()
 2010-06-19 09:39:23   this is the MySQL datetime
我猜最上面的是unix时间?一直在玩弄strotime,但没有取得多大成功


欢迎任何帮助

为什么要混合使用PHP时代和MySQL时代

相反,直接在MySQL中进行比较:

要获取MySQL中的当前日期/时间,请使用NOW函数。例如,您可以比较2010-06-19 09:39:23' 这将检查列中的给定日期是否早于24小时

如果绝对有必要将MySQL时间戳转换为UNIX时间戳,可以使用MySQL的UNIX_时间戳函数进行转换。

没有成功

echo strtotime("2010-06-19 09:39:23");
给我

1276940363
mktime9、39、23、6、19、2010给出了相同的时间,因此解析工作正常

要获得以秒为单位的差异,可以减去时间戳,例如

$diff = time() - strtotime("2010-06-19 09:39:23");
如果差异大于86400 60*60*24秒,则时间戳间隔超过一天:

if(time() - strtotime("2010-06-19 09:39:23") > 60*60*24) {
   // timestamp is older than one day
}
您还可以执行以下操作:

SELECT * FROM my_table WHERE timestamp < NOW() - INTERVAL 1 DAY;

我写了一个函数,通过它你可以确定第一个给定的日期是比第二个给定的日期大一天还是小n天

$date1 = "2013/03/01";
$date2 = "2013/03/01";
$sign  = "-";
$diff  = 1;
$result = isDaysSmallerBigger($date1, $date2, $sign, $diff);
var_dump($result);

/**
 * Note: this function is only supported in php 5.3 or above
 * 1. If $date1 - $date2 = $sign $diff days, return true;
 * 2. If $date1 equals $date2 and $diff euqals 0, whether $sign is "+" or "-", return true
 * 3. Else return false; 
 * @param unknown_type $date1
 * @param unknown_type $date2
 * @param string $sign: "-": $date1 < $date2; "+": $date1 > $date2; 
 * Besides if $diff is 0, then both "-" and "+" means $date1 === $date2;
 * @param integer $diff: date difference between two given dates
 */
function isDaysSmallerBigger($date1, $date2, $sign, $diff) {
    $dateTime1 = new DateTime($date1);
    $dateTime2 = new DateTime($date2);

    $interval = $dateTime2->diff($dateTime1);
    $dayDiff  = $interval->format('%a');
    $diffSign = $interval->format('%R'); 

    if((int)$dayDiff === (int)$diff) {
        // Correct date difference

        if((int)$diff !== 0) {
          // Day difference is not 0
          if($diffSign === $sign) {
            return true;
          } else {
            return false;
          }
        } else if((int)$diff === 0) {
          // Day difference is 0, then both given "+" and "-" return true
          return true;
        } 
    } else {
        // Incorrect date difference
        return false;   
    }   
}

非常感谢,今天我的头好像没拧好!我会这样做,但目前还没有访问查询的权限,所以我需要使用返回的值来执行查询。