We just need to pass start date and end date to get collection between Specific time in Magento 2. We need to filter created_at field using addAttributeToFilter(). Create Block file.
By default created_at field in sales_order table represent the time of order creation in Magento 2.
<?php namespace Rbj\Order\Block; 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('2018-1-1')); // start date $endDate = strtotime("Y-m-d h:i:s", strtotime('2018-10-1')); // end date $orders = $this->orderCollectionFactory->create() ->addAttributeToFilter('created_at', array('from'=>$startDate, 'to'=>$endDate)); return $orders; } ?>
Call Function from template file,
$orders = $block->getOrderCollectionByDateRange(); if($orders->getTotalCount() > 0) { foreach($orders as $_order) { $orderId = $_order['increment_id']; echo "<pre>";print_r($_order); } }
You can get Order collection by date range by the above tricks.