Set created_at When Programmatically Creating a Magento Order

datemagento-1.8orders

I'm struggling to set the order date when creating a magento order programatically.

Here is what I'm trying to use:

$orderObj->setData('created_at', $date);
$orderObj->setUpdatedAt($date);

but it doesn't appear to work.

Thank you in advance!

Best Answer

created_at and updated_at for orders is set in Mage_Sales_Model_Resource_Abstract::_prepareDataForSave():

/**
 * Prepare data for save
 *
 * @param Mage_Core_Model_Abstract $object
 * @return array
 */
protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
{
    $currentTime = Varien_Date::now();
    if ((!$object->getId() || $object->isObjectNew()) && !$object->getCreatedAt()) {
        $object->setCreatedAt($currentTime);
    }
    $object->setUpdatedAt($currentTime);
    $data = parent::_prepareDataForSave($object);
    return $data;
}

You can see that updated_at is always set to the current time, whereas created_at is only set if the attribute is empty. The format that it should have comes from Varien_Date.

So you should be able to define your own creation timestamp:

$order->setCreatedAt(Varien_Date::formatDate($date, false));

where $date can be a Unix timestamp or an arbitrary date expression that can be parsed with PHPs strtotime