Search code examples
phpdatetimeintervals

DateTime()->sub/add vs DateTime->modify


I am writing code that will do 3 queries to select items that expire within 30 days, 60 days and 90 days:

$arrDates = array("30"=>array(), "60"=>array(), "90"=>array());
$sDateFormat = 'Y-m-d';
$sQuery = "SELECT *
            FROM `table
            WHERE `expiry_date` BETWEEN "; // Ranges will be added later

foreach ($arrDates as $sInterval=>$arrContainer)
{
    $dtStart = new DateTime();
    $dtEnd = new DateTime();
    $sRangeStart = $dtStart->add(new DateInterval("P{$sInterval}D"))->format("{$sDateFormat} 00:00:00");
    $sRangeEnd = $dtEnd->add(new DateInterval("P{$sInterval}D"))->format("{$sDateFormat} 23:59:59");

    $arrDates[$sInterval] = fetch_all($sQuery . "'{$sRangeStart}' AND '{$sRangeEnd}'");
}

This code works without any issues. A colleague has suggested that I replace the code inside the foreach loop with the following:

$dtStart = new DateTime();
$dtEnd = new DateTime();
$dtStart->modify("+{$sInterval} days")->setTime(0, 0, 0)->format("{$sDateFormat} 00:00:00");
$dtEnd->modify("+{$sInterval} days")->setTime(23, 59, 59)->format("{$sDateFormat} 23:59:59");

$arrDates[$sInterval] = fetch_all($sQuery . "'{$sRangeStart}' AND '{$sRangeEnd}'");

His reasoning behind this change being that it would mean not having to instantiate 2 DateIntervals every loop. I do not agree with his reasoning mainly because ->modify is an older way of date modification, and I'm not 100% convinced that his way would mean an increase in performance (even though the performance hit we would take either way would be negligible).

If anyone could provide evidence for which way is better (either way is welcome), I'd be most grateful!


Solution

  • Both ways are pretty the same, it's a matter of taste how to write code.

    For my taste $dt->modify('+5 days') is more readable than $dt->add(new DateInterval("P5D"))

    As for performance, below is a code to test it and results are:

    $dt->modify('+5 days') - 0.0503 sec

    $dt->add(new DateInterval("P5D")) - 0.0572 sec

    so, the readable code is also a very little faster one for the case from the question :)

    <?php
    
        $i = 0;
        $start = microtime(true);
        while($i++ < 10000) {
            $date = new DateTime('2018-02-13');
            $date->modify('+5 days');
        }
        $end = microtime(true);
    
        echo $end - $start, "\n";
    
        $i = 0;
        $start = microtime(true);
        while($i++ < 10000) {
            $date = new DateTime('2018-02-13');
            $date->add(new DateInterval('P5D'));
        }
        $end = microtime(true);
    
        echo $end - $start, "\n";