PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] How to handle Query builder with date formats

 March 11, 2022     cakephp, cakephp-4.x, query-builder     No comments   

Issue

I would like to show only the events for which startdate begins as of tomorrow. How can I proceed ? For the moment it's taking h:i:s into account as well.

public function display()
{
    $now = date('Y-m-d H:i:s');

    $this->loadModel('Events');
    $events = $this->Events
        ->find()
        ->contain(['Categories', 'Venues'])
        ->limit(5)
        ->order(['events.startdate' => 'ASC'])
        ->where(['events.startdate >' => $now]);
    $this->set('upcomingEvents', $events);
}

I tried this but it's not working:

public function display()
{
    $now = date('Y-m-d');

    $this->loadModel('Events');
    $events = $this->Events
        ->find()
        ->contain(['Categories', 'Venues'])
        ->limit(5)
        ->order(['events.startdate' => 'ASC'])
        ->where(['date_format("%Y-%m-%d", events.startdate)' => $now]);
    $this->set('upcomingEvents', $events);
}

Solution

No need to format the date in the query and lose the indexing functionality, instead compare against a datetime string that uses 00:00:00 for the time part, eg the start of the day.

You can achieve this easily with date('Y-m-d 00:00:00'), however that would be today, not tomorrow, you'd need to feed date() with a timestamp like date('Y-m-d 00:00:00', strtotime('+1 day')).

You can also use the datetime functionality that ships with CakePHP. Today \Cake\Chronos\Date::tomorrow() would create a date object representing 2021-10-06 where the time part will always be 00:00:00.

->where(['Events.startdate >=' => \Cake\Chronos\Date::tomorrow()])

The ORM will automatically format the date object accordingly to the column type, so for your I suppose DATETIME column, it would end up as 2021-10-06 00:00:00 in the SQL.

See also

  • Cookbook > Date & Time
  • Chronos Cookbook


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing