Get orders collection between a date range in magento 2.

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.

How to get order item collection by item id magento 2?

You can get item collection data by Item id in Magento 2 by using below code snippet, Create Block file,

<?php
namespace Rbj\Training\Block;

class Item extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template $context,
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
        array $data = []
    ) {
        $this->orderItemRepository = $orderItemRepository;
        parent::__construct($context, $data);
    }

    /* get order Item collection */
    public function getOrderItem($itemIid)
    {
        $itemCollection = $this->orderItemRepository->get($itemId);
        return $itemCollection;
    }
}

Call function from the Template file,

$itemId = 10; // order item id
$getItemCollection = $block->getOrderItem($itemId);
echo $getItemCollection->getOrderId();
echo "<pre>";print_r($getItemCollection->debug());

How to create order programmatically in magento 2?

Magento 2 You can create order programmatically by simple coding.

You need to Create custom quote for order and based on that you can convert the quote to Order in Magento 2 by a simple code.

Create order information from the template file to helper file.

<?php
$orderInfo =[
    'currency_id'  => 'USD',
    'email'        => 'rakesh.jesadiya@testttttttt.com', //customer email id
    'address' =>[
        'firstname'    => 'Rakesh',
        'lastname'     => 'Testname',
        'prefix' => '',
        'suffix' => '',
        'street' => 'B1 Abcd street',
        'city' => 'Los Angeles',
        'country_id' => 'US',
        'region' => 'California',
        'region_id' => '12', // State region id
        'postcode' => '45454',
        'telephone' => '1234512345',
        'fax' => '12345',
        'save_in_address_book' => 1
    ],
    'items'=>
        [
            ['product_id'=>'1','qty'=>1], //simple product
            ['product_id'=>'67','qty'=>2,'super_attribute' => array(93=>52,142=>167)] //configurable product, pass super_attribte for configurable product
        ]
];
$helper = $this->helper('Rbj\Training\Helper\Data');
$orderData = $helper->createOrder($orderInfo);

?>

In above order info, We take customer basic details and Items info.
We have taken a simple and configurable product item. For configurable product, We need to pass super_attribute array value. For Test purpose, I have taken Magento Sample data configurable and simple product id.

For Configurable, 93 is Color attribute id where 52 is Gray option id.
142 is size attribute id where 167 is for XS size option id, you need to pass the dynamic value for a configurable product.

Create helper file,

Let’s say Data.php file location at, app/code/Rbj/Training/Helper/Data.php

<?php
/**
 * ExtendedRma Helper
 */
namespace Rbj\Training\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender

    ) {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->productRepository = $productRepository;
        $this->customerRepository = $customerRepository;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->orderSender = $orderSender;
        parent::__construct($context);
    }
    /*
    * create order programmatically
    */
    public function createOrder($orderInfo) {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderInfo['email']);// load customet by email address
        if(!$customer->getId()){
            //For guest customer create new cusotmer
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderInfo['address']['firstname'])
                    ->setLastname($orderInfo['address']['lastname'])
                    ->setEmail($orderInfo['email'])
                    ->setPassword($orderInfo['email']);
            $customer->save();
        }
        $quote=$this->quote->create(); //Create object of quote
        $quote->setStore($store); //set store for our quote
        /* for registered customer */
        $customer= $this->customerRepository->getById($customer->getId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer

        //add items in quote
        foreach($orderInfo['items'] as $item){
            $product=$this->productRepository->getById($item['product_id']);
            if(!empty($item['super_attribute']) ) {
                /* for configurable product */
                $buyRequest = new \Magento\Framework\DataObject($item);
                $quote->addProduct($product,$buyRequest);
            } else {
                /* for simple product */
                $quote->addProduct($product,intval($item['qty']));
            }
        }

        //Set Billing and shipping Address to quote
        $quote->getBillingAddress()->addData($orderInfo['address']);
        $quote->getShippingAddress()->addData($orderInfo['address']);

        // set shipping method
        $shippingAddress=$quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod('flatrate_flatrate'); //shipping method, please verify flat rate shipping must be enable
        $quote->setPaymentMethod('checkmo'); //payment method, please verify checkmo must be enable from admin
        $quote->setInventoryProcessed(false); //decrease item stock equal to qty
        $quote->save(); //quote save 
        // Set Sales Order Payment, We have taken check/money order
        $quote->getPayment()->importData(['method' => 'checkmo']);
 
        // Collect Quote Totals & Save
        $quote->collectTotals()->save();
        // Create Order From Quote Object
        $order = $this->quoteManagement->submit($quote);
        /* for send order email to customer email id */
        $this->orderSender->send($order);
        /* get order real id from order */
        $orderId = $order->getIncrementId();
        if($orderId){
            $result['success']= $orderId;
        }else{
            $result=['error'=>true,'msg'=>'Error occurs for Order placed'];
        }
        return $result;
    }

You got a result as array for success order place, Array ( [success] => ‘OrderId’ )