Get Daily Order Summary from Magento

Get Magento Orders for Today with the Difference between server timezone and local timezone

Posted on March 18, 2016 in Magento, PHP

Today, I was asked by my client to generate a report module to show her the total amounts of orders and total order numbers. When I started to code the module, I found there is always a discrepancy between the result I got and the one from the backend. So I use PHP method date_default_timezone_get() to get the server’s timezone, which is set as ‘UTC’. But our local timezone is Los Angeles. There are 8 hours difference between them, which is 28800 second.

The working code is shown as following:


       $start = date('Y-m-d', time());
        $now = date('Y-m-d H:i:s', time());
        $from = date('Y-m-d H:i:s', strtotime($start . "+28800 seconds"));
        $to = date('Y-m-d H:i:s', strtotime($now . "+28800 seconds"));


        $orders = Mage::getModel('sales/order')
            ->getCollection()
            ->addFieldToFilter('status', array('neq'=>'canceled'))
            ->addFieldToFilter('created_at', array('from'=>$from, 'to'=>$to));
        $sum = 0;
        $totalOrders = 0;
        foreach($orders as $order) {
            $itemTotal = $order->getData('grand_total');
            if($itemTotal > 0){
                $sum += $itemTotal;
                $totalOrders++;
            }
        }

        echo 'Total Orders #: '. $totalOrders;
        echo "<br>Total for $start: " . Mage::helper('core')->currency($sum, true, false);

After adding 28800 seconds to ‘UTC’ timezone, I finally got the correct answer. I hope this code will help someone is struggling the same problem.


comments powered by Disqus