How to Get Orders Collection Between a Date Range in Magento 2

How to Get Orders Collection between a Date Range in Magento 2?

In today’s tutorial, we will help you with a step by step guide to get orders collection between a date range in Magento 2. All we need to do is pass the start date and end date to get collection between a specific time in Magento 2.

It is required to filter created_at field using addAttributeToFilter().

Step 1: Create a Block file.
created_at field in  sales_order table represents the time of order creation in Magento 2 by default.

<?php

class OrderRange extends \Magento\Framework\View\Element\Template
{
 public function __construct(
 \Magento\Framework\View\Element\Template\Context $context,
 \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
 array $data = []
 ) {
 $this->orderCollectionFactory = $orderCollectionFactory;
 parent::__construct($context, $data);
 }
/* Order collection between start and end date */
 public function getOrderCollectionByDateRange(){
 $startDate = date("Y-m-d h:i:s",strtotime('2020-12-1')); // start date
 $endDate = strtotime("Y-m-d h:i:s", strtotime('2020-11-1')); // end date
$orders = $this->orderCollectionFactory->create()
 ->addAttributeToFilter('created_at', array('from'=>$startDate, 'to'=>$endDate));
 return $orders;
 }
?>

Now, call Function from the template file:

$orders = $block->getOrderCollectionByDateRange();
if($orders->getTotalCount() > 0) { 
 foreach($orders as $_order) {
 $orderId = $_order['increment_id'];
 echo "<pre>";print_r($_order);
 }
}

We hope that we have covered everything related to order collection in a specific date range. If still need our professional help with Magento eCommerce Development, feel free to contact us.

 

Tags