Asked  7 Months ago    Answers:  5   Viewed   44 times

What is the simplest way to get the difference in days between two PHP DateTimes, considering midnight as a day change (just like the DATEDIFF(DAY) SQL function does)?

For example, between today at 13:00 and tomorrow at 12:00, I should get 1 (day), even though the interval is less than 24 hours.

$date1 = new DateTime("2013-08-07 13:00:00");
$date2 = new DateTime("2013-08-08 12:00:00");
echo $date1->diff($date2)->days; // 0

 Answers

30

You could ignore the time portion of the date string

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00")));
$date2 = new DateTime(date('Y-m-d', strtotime("2013-08-08 12:00:00")));
echo $date1->diff($date2)->days; // 1
Wednesday, March 31, 2021
 
Domiik
answered 7 Months ago
94

This is not a duplicate question per se, so here a solution that might work for you:

$productId = {PRODUCT_ID};
$orders = array();
$collection = Mage::getResourceModel('sales/order_item_collection')
    ->addAttributeToFilter('product_id', array('eq' => $productId))
    ->load();
foreach($collection as $orderItem) {
    $orders[$orderItem->getOrder()->getIncrementId()] = $orderItem->getOrder();
}

You'll end up with an array of orders which contain an orderitem for the given {PRODUCT_ID}.

Wednesday, March 31, 2021
 
Baba
answered 7 Months ago
24

You need to call DateInterval::format() to display that difference as a string.

echo $diff->format('%d days');

See the manual for all of the available formatting options.

Wednesday, July 7, 2021
 
mattltm
answered 4 Months ago
33

Well, it sounds like you want the difference in the number of days, ignoring the time component. A DateTime with the time component reset to 00:00:00 is what the Date property gives you:

(startDate.Date - endDate.Date).TotalDays
Monday, August 9, 2021
 
Tak
answered 3 Months ago
Tak
71

The behavior is correct. Both date intervals represent same number of days (364). The month and date part represent the period that needs to be added to/subtracted from first date to reach second date:

1981-11-20 minus 1980-11-21 represents an interval of 11 month 30 day
1980-11-21 + 11 month = 1981-10-21
1981-10-21 + 30 day   = 1981-10-21

1980-11-21 minus 1981-11-20 represents an interval of 11 month 29 day
1981-11-20 - 11 month = 1980-12-20
1980-12-20 - 29 day   = 1980-11-21

A simpler example would be Oct 21 ... Dec 20:

  • You need to add 1 month 29 days to Oct 21 to reach Dec 20 (note that month before Dec has 30 days)
  • But ... you need to subtract 1 month 30 days from Dec 20 to reach Oct 21. Oct itself has 31 days which explains the difference.
Sunday, August 15, 2021
 
ala
answered 2 Months ago
ala
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :