If you are working with Magento 2, you may often need to find the order collection for specific days or date range. It may be required to perform various actions such as send a thank you Email for the complete orders, delete the pending orders, display the order collection and last, check the revenue based on days!
Here, I’m showing you how to get Magento 2 order collection based on “Number of Days” conditions such as:
- Get order collection of a particular day
- Get order collection of a date range
- Get order collection of last “X” number of days.
Method to Get Magento 2 Order Collection Based on “Number of Days” Condition:
Get order collection of a particular day:
$orderCollection = $objectManager->get('Magento\Sales\Model\ResourceModel\Order\CollectionFactory'); $prev_date = date('Y-m-d', strtotime('-7 days')); $collection = $orderCollection->create() ->addAttributeToFilter('status', ['in' => 'pending']) ->addAttributeToFilter('created_at', ['gteq'=>$prev_date.' 00:00:00']) ->addAttributeToFilter('created_at', ['lteq'=>$prev_date.' 23:59:59']);
Get order collection of a date range or of last “X” number of days:
$orderCollection = $objectManager->get('Magento\Sales\Model\ResourceModel\Order\CollectionFactory'); $prev_date = date('Y-m-d', strtotime('-7 days')); $current_date = date('Y-m-d'); $collection = $orderCollection->create() ->addAttributeToFilter('status', ['in' => 'pending']) ->addAttributeToFilter('created_at', ['gteq'=>$prev_date.' 00:00:00']) ->addAttributeToFilter('created_at', ['lteq'=>$current_date.' 23:59:59']);
That’s it.
Thank you.