How to Get Magento 2 Order Collection Based on “Number of Days” Condition
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:
1234567$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:
12345678$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.
If you face any difficulty in any of the implementations of the above conditions, feel free to post the doubts in the Comments section below. I’d be happy to help.
Do not forget to rate the post with 5 stars.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Hi Sanjay,
Is this code will work for Magento 2.4.0 ? and How to i can convert this code into extension ? i want to show these orders in Admin Dashboard custom extension. How to i;ll do that ? Kindly guide me on this.
Kind Regards,
Hello Wajahat,
Yes, the above code will work for Magento 2.4.0 as well.
If you want to create a grid to display the orders then you need to add the code in your collection file.
Thank You