magentoproductdatecreated

Magento - look up products created in the last hour


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?


Solution

  • 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)