Magento – Magento 2: Order getCreatedAt() returns null

dependency-injectionmagento-enterprisemagento2orderssales-order

I meet a very strange situation while working with event observer in Magento 2.

My custom module hooked into sales_order_save_after (which returns \Magento\Sales\Model\Order), and its magic methods work fine but getCreatedAt()

The only way to get date time in this case is using this getCreatedAtFormatted() instead of getCreatedAt().

Anyone can please tell me what was happening?

Best Answer

See how getCreatedAtFormatted is declared:

public function getCreatedAtFormatted($format)
{
    return $this->timezone->formatDateTime(
        new \DateTime($this->getCreatedAt()),
        $format,
        $format,
        null,
        $this->timezone->getConfigTimezone('store', $this->getStore())
    );
}

It uses $this->getCreatedAt() to create DateTime and if you create DateTime like new \DateTime(null) you get current date.

The above means that if you have no value for created_at data of order, you are still going to get valid \DateTime object.

This is why getCreatedAtFormatted works and getCreatedAt is not.

Now all you need to figure out is why order is lacking created at value.

My guess is, that created_at is added by a timestamp update in the table, and to get its value, you may need to call $order->load($order->getId())

Related Topic