Magento API: Select Orders by Date Range

Here’s snippet of code I was able to use to get all of yesterday’s orders. You can see more variations for the use of DateTime here. I also wrote a front end to allow a selection of dates, but you can figure that out. This was the hard part to me. How the heck do I pass the from and to dates to Magento’s sales_order.list call?

Also note that Magento internally store dates and times in UTC. So I have to convert to that offset to get my orders in my local time. time_local_to_utc is a little function I wrote to do that. Conversely, time_utc_to_local converts it back. (Code later in this post).

Remember, much of the code I publish here is very specific for a particular implementation. This code is designed to be able to pull back all payment information into a spreadsheet for an accounting department. This is not a generic solution to a generic Magento problem. Rather, I intended this to help other folks get a start on pulling back orders by date!

$day = new DateTime();
$day->modify( "-1 day" );
 
$fromDate = $day->format("Y-m-d 00:00:00");
$toDate = $day->format("Y-m-d 23:59:59" );
 
$utc_from=time_local_to_utc($fromDate);
$utc_to=time_local_to_utc($toDate);
 
$proxy = new SoapClient('YOURSITE/api/soap/?wsdl');
$sessionId = $proxy->login('YUOUR_LOGIN', 'YOUR_PASS');
$order_headers = $proxy->call($sessionId, 'sales_order.list',
        array(
            array(
                'created_at'=>
                    array(
                        'from'=>$utc_from,
                        'to'=>$utc_to
                    )
                )
            )
        );
$howManyOrders = count($order_headers);

Here are the 2 time functions. They could certainly be made more general and really should be refactored (pass in “to” and “from” zones…), but you get the idea. And maybe there’s something to be said for the inline main code being simple to read.

function
time_local_to_utc($date) {
    $dt = new DateTime($date, new DateTimeZone("America/New_York"));
    $dt->setTimezone(new DateTimeZone("UTC"));
    return( $dt->format("Y-m-d H:i:s") );
}
 
function
time_utc_to_local($date) {
    $dt = new DateTime($date, new DateTimeZone("UTC"));
    $dt->setTimezone(new DateTimeZone("America/New_York"));
    return( $dt->format("Y-m-d H:i:s") );
}

Facebook comments: