1

我有一个格式为日期和时间的字符串2013-07-01 19:10:05 (Y-m-d H:i:s)。当我从存储日期和时间的数据库中输出数据时,我想查看自该日期和时间以来是否已经过去了三天。

示例:存储在数据库中的是2013-07-01 00:00:00. 3 天后存储的日期和时间将是2013-07-03 00:00:00

如果那是真的,我想回应一些文字。

我尝试了以下方法,但我认为我完全不在航行。

if( strtotime('-3 days') < strtotime($row["orderdatetime"]) ) {
   echo " <img src='imgs/warning.png' ></td >";
}

感谢您提供任何帮助!

真诚的,安德烈亚斯

编辑:

这就是我的 PHP 脚本的样子。

if ($row["confirmeddatetime"] == "0000-00-00 00:00:00" ) {
        $db_datetime = new DateTime($row['orderdatetime']);
        $db_plus_three = $db_datetime->add(new DateInterval('P3D'));
        $now_datetime = new DateTime();
        if ($db_plus_three < $now_datetime) {
            echo " <img src='imgs/warning.png' ></td >";
        } else {
            echo "</td >";
        }

你们中的任何人都可以确定是否有问题吗?

4

5 回答 5

3

我建议使用 DateTime 和 DateInterval 类。

$db_datetime = new DateTime($row['orderdatetime']);
$db_plus_three = $db_datetime->add(new DateInterval('P3D'));
$now_datetime = new DateTime();

if ($db_plus_three < $now_datetime) {
   // this is more than 3 days old
}

另一种方法是在数据库查询本身中设置一个标志,如下所示:

SELECT
    [YOUR CURRENT FIELDS HERE],
    (CASE WHEN NOW() > DATE_ADD(orderdatetime, INTERVAL 3 DAYS) THEN 1 ELSE 0) AS three_days_old
    [REST OF QUERY HERE]

three_days_old然后,您可以通过查看该项目是否超过 3 天的价值来轻松识别。

于 2013-07-02T22:09:06.990 回答
1

可能最简单的方法是直接从数据库中获取 unix 时间(假设是 mysql):

SELECT *, UNIX_TIMESTAMP(orderdatetime) AS ordertimestamp...

那么在你的比较中你只需要

if( strtotime('-3 days') < $row["ordertimestamp"] ) {
   echo " <img src='imgs/warning.png' ></td >";
}
于 2013-07-02T21:59:24.907 回答
0

strtotime 将时间字符串转换为时间戳,它只是整数秒。只需比较时间减去 3 * 86400(一天中的秒数)

于 2013-07-02T21:59:39.830 回答
0
SELECT (orderdatetime <= NOW() + INTERVAL 3 DAY) AS threedays ...

如果 3 天过去与否,您将获得 1/0 真/假值。我建议不要在 PHP 中进行这样的比较,因为您将强制使用 mysql 日期 -> 字符串 -> int -> 日期转换链,当您可以直接在 mysql 中进行比较时会浪费大量 CPU 周期。

于 2013-07-02T22:01:53.553 回答
0

实际上,您的第二个示例对我有用,请注意该add()功能,它会更新值本身。这是我自己如何使用它的类似示例:

/**
 * Checks if the elapsed time between $startDate and now, is bigger
 * than a given period. This is useful to check an expiry-date.
 * @param DateTime $startDate The moment the time measurement begins.
 * @param DateInterval $validFor The period, the action/token may be used.
 * @return bool Returns true if the action/token expired, otherwise false.
 */
function isExpired(DateTime $startDate, DateInterval $validFor)
{
  $now = new DateTime();

  $expiryDate = clone $startDate;
  $expiryDate->add($validFor);

  return $now > $expiryDate;
}

// how to use it
$startDate = new DateTime('2013-06-16 12:36:34');
$validFor = new DateInterval('P3D'); // valid for 3 days
$isExpired = isExpired($startDate, $validFor);
于 2013-07-03T19:51:10.190 回答