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:It uses
$this->getCreatedAt()
to createDateTime
and if you createDateTime
likenew \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 andgetCreatedAt
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())