【问题标题】:CakePHP 3 : date comparison in viewCakePHP 3:视图中的日期比较
【发布时间】:2016-11-16 10:15:35
【问题描述】:

我正在开发 CakePHP 3.2。

我想将数据库中timestamp 的日期与CakePHP 的isThisMonth() 函数进行比较。

我列出了created 日期在1 month 内的产品。它将显示带有产品的NEW 徽章。

这是我在视图中所做的

<?php $date = new DateTime($product->created);
      $date = $date->format('Y-m-d');
      if ($date->isThisMonth()): ?>   // error is pointing this line
         <span class="new-product"> NEW</span>
<?php endif; ?>

这里$product 是错误项,created 是数据库中的时间戳列。

但这会产生错误

Call to a member function isThisMonth() on string

【问题讨论】:

    标签: cakephp date-comparison cakephp-3.2


    【解决方案1】:

    尝试在$date = $date-&gt;format('Y-m-d');下方添加此内容

    $time = new Time($date);
    

    然后将$date-&gt;isThisMonth()):$time-&gt;isThisMonth()): 交换

    http://book.cakephp.org/3.0/en/core-libraries/time.html#comparing-with-the-present

    view.ctp 中包含use Cake\I18n\Time;

    【讨论】:

    • 已解决.. 刚刚在view.ctp 文件中添加了use Cake\I18n\Time;
    • 你打败了我。
    • 这听起来过于复杂。为什么要使用 DateTime 对象,将其格式化为字符串,然后再转换回对象,而不是首先使用您拥有的对象?
    • 你说得很对,但问题明确表示他们想使用蛋糕功能isThisMonth(),因此有必要创建一个Time 对象。我没有仔细看,但也许$date = new DateTime($product-&gt;created); 可以替换为$time = new Time($product-&gt;created);,这样可以简化事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多