繁体   English   中英

检查数据是否旧于当前时间php

[英]Check if data is older then the current time php

我正在尝试检查数据库中的行时间和某列是否早于今天,然后再回显成功,但是它正在回显某个明天的成功!

// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');

    // Start Expired password check and drop function
    function cronexec_expired ($timenow) {

        include('../../config.php');

        // Open up a new MySQLi connection to the MySQL database
        mysql_connect($dbHost, $dbUsername, $dbPassword);
        mysql_select_db($dbTable);

        // Query to check the status of the code input
        $expiry_check = "SELECT * FROM code_log WHERE status='Unused'";

        // Run the query
        $expiry_checkexec = mysql_query($expiry_check);

        while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {

            echo $expiry_possibles[6] . '<br /><br />';
            echo $timenow . '<br /><br />';

            if (date('l jS \of F Y h:i:s A', strtotime($expiry_possibles[6]) < $timenow)) {

                echo "Success";

            }


        }


    }

$ expiry_possibles [6]值

Monday 9th of September 2013 12:46:20 PM

是时候了

Sunday 8th of September 2013 01:35:22 PM

任何意见,将不胜感激

我不明白您为什么要使用完整日期,所以没有必要。 相反,如何使用unix时间戳? 参见http://php.net/manual/en/function.time.php 比较可能很难比较完整的日期字符串?

我总是发现使用time()容易得多,因为它基本上比较了两个数字。

$current_time = time();
$expiry_possibles_timestamp = strtotime($expiry_possibles[6]);

if ($current_time > $expiry_possibles_timestamp)
{
    // Older than current time
}

我已经在下面修改了您的代码,请尝试一下。 请记住,您将需要PHP 5.3及更高版本。

function cronexec_expired($timenow)
{

    include('../../config.php');

    // Open up a new MySQLi connection to the MySQL database
    mysql_connect($dbHost, $dbUsername, $dbPassword);
    mysql_select_db($dbTable);

    // Query to check the status of the code input
    $expiry_check = "SELECT * FROM code_log WHERE status='Unused'";

    // Run the query
    $expiry_checkexec = mysql_query($expiry_check);

    while ($expiry_possibles = mysql_fetch_array($expiry_checkexec))
    {
        echo $expiry_possibles[6] . '<br /><br />';
        echo $timenow . '<br /><br />';

        $datetime = DateTime::createFromFormat('l jS \of F Y h:i:s', $expiry_possibles[6]);

        if (!$datetime) continue; // Skip this execution as we cannot parse the date, so we will not trust it.

        if (time() > $datetime->getTimestamp())
        {
            echo "Database row is in the past";
        } else
        {
            echo "Database row is in the future";
        }

    }

}

尽管我还没有测试过,但这应该可以。 日期如何存储在数据库中? 它应为MySQL格式(YYYY-MM-DD HH:MM:SS)或unix时间戳格式。

我建议使用DateTimeDateInterval类。

如果差异恰好是一天,您可以让他们进行比较:

$expiry = new DateTime($expiry_possibles[6]);
if ($expiry->diff($time_now)->format('%d') == "1") ...

或相反亦然。 还有一个过程接口,形式为date_diff()

更多信息: http : //www.php.net/manual/en/datetime.diff.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM