4

I'm trying to look up products created in the last hour.

I'm able to sort products by created date like so:

$collection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToSort('created_at', 'desc');

But I'd like to filter by created_at. I've tried replacing the last line of the above block with addAttributeToFilter('created_at', array('gteq' =>$time));, which I think must be right, but I can't find the right format for $time.

Am I on the right track here, and if so, what format should I be feeding $time in with?

Markie
  • 760
  • 17
  • 32

1 Answers1

3

You should use the MySQL timestamp format. The following code worked for me:

$time = "2013-02-06 09:32:23"; // 'yyyy-mm-dd hh:mm:ss'

$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToSort('created_at', 'desc')
->addAttributeToFilter('created_at', array('gteq' =>$time));

You can quite easily find the format of a given attribute, by simple echoing it to your screen. For example:

$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToSort('created_at', 'desc');

exit($collection->getFirstItem()->getData('created_at');

The output for that was 2013-02-06 09:32:23 (on my environment)

Menno
  • 641
  • 4
  • 13
  • Brilliant, thank you! That's a 100% fix. I don't know why I was struggling with that, it looks so obvious now. – Markie Mar 07 '13 at 13:00
  • "Now that I've figured it out, it looks so obvious" is my motto when working with Magento. Don't feel too bad about it. – Mike Mar 07 '13 at 14:23