【问题标题】:PHP: check datetime to see if it's coming upPHP:检查日期时间以查看它是否即将到来
【发布时间】:2023-04-03 15:01:01
【问题描述】:

我从数据库中获得了一个 DATETIME,我需要能够检查该日期是否在从现在起 30 天内。

$renewal_date = $row['renewal_date'];
$current_time = new DateTime();
$interval = $renewal_date->diff($current_time);

这对我不起作用。

【问题讨论】:

  • $renewal_date 是 DateTime 对象吗?
  • strtotime 是一个不错的起点,我认为php.net/manual/en/function.strtotime.php
  • 这不会使它成为 PHP DateTime 对象。做var_dump($renewal_date);看看。
  • 检查 $renewal_date 和 $current_time 的格式是否相同...???(如 'mm-dd-yy' 或 'yy-dd-mm')

标签: php sql date datetime


【解决方案1】:

试试这样的

$renewal_date = new DateTime($row['renewal_date']);
$cutoff= new DateTime('+31 days 00:00');


if ($renewal_date < $cutoff && $renewal_date >= new DateTime)
    echo 'Renewal Time!';
else
    echo 'All OK!';

如果您想显示过去日期的续订,请删除 && 条件

【讨论】:

  • 我开始注意到一个缺陷......从现在开始,CRON 作业能够准确地在“30 天”内运行的机会几乎为零。那么我怎样才能在合理的范围内抓住这种更新呢?
  • 我不确定你的意思?我更新了我的答案,以便它永远是第 30 天的午夜。因此,如果您每天运行您的 cron,它总是会检查正常。记住它是
  • 是的,你上面做的正是我需要的!
  • +1 啊!现在我明白了。 DateTimeclass 真的存在!但要小心,是否兼容 5.2+...
【解决方案2】:

您确定 $row['renewal_date'] 是 DateTime 对象吗?

我的印象是,这是您从数据库而不是 DateTime 对象中获取的值。

试试 var_dump($renewal_date) 如果这是一个包含日期值的字符串,你应该使用类似的东西:

$renewal_date = new DateTime ($row['renewal_date']);
$current_time = new DateTime();
$interval = $renewal_date->diff($current_time);

【讨论】:

    【解决方案3】:

    $renewal_date 不是 PHP DateTime 对象。您可以通过var_dump($renewal_date); 进行验证。

    查看DateTime::diff 手册中的示例。您需要使用以下方式将日期转换为 DateTime 对象:

    $datetime1 = new DateTime($renewal_date);
    

    那么它应该可以工作了。

    【讨论】:

      【解决方案4】:
      $renewal_date = strtotime($renewal_date); // maybe need it depending of sql format of date
      
      if (abs($renewal_date - time()) < 86400*30)
      {
          echo 'less than 30 days from now';
      }
      

      编辑 1

      abs($renewal_date - time()) 给出了从现在开始的一段时间(time())它应该指的是未来。事实上,这种情况也可以用于过去的时期......

      &lt; 86400*30说,失误肯定低于30天……

      那是我的 2 美分:)

      【讨论】:

      • 一天中的秒数。进行这种比较 IMO 的不好方法。
      • @sachleen 为什么会这样? 30days=86400secs*30 正好。
      • 因为阅读它并不清楚发生了什么。还有leap second.
      • 是的,但是@sachleen 您还没有准确回答如何确定“renewal_date”是否比现在少 30 天
      • @sachleen 我知道你在说什么我正在以更精确的方式工作,但问题清楚地表明这是一个简单的比较。 30 天...
      猜你喜欢
      • 1970-01-01
      • 2011-12-27
      • 2011-08-15
      • 2019-12-14
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      相关资源
      最近更新 更多