Search code examples
phplaravellaravel-5.6php-carbon

count occurrence of date (e.g 14th) between two dates


How can I count occurrences of 14th of a month between two dates
For example between 07.05.2018 and 04.07.2018 I have 2 occurrences of the 14th


Solution

  • Try this. Note that I've changed your date format, but you can just do a createFromFormat if you're really keen on your own format.

    $startDate = new DateTime('2018-05-07');
    $endDate = new DateTime('2018-07-04');
    
    $dateInterval = new DateInterval('P1D');
    $datePeriod = new DatePeriod($startDate, $dateInterval, $endDate);
    
    $fourteenths = [];
    
    foreach ($datePeriod as $dt) {
        if ($dt->format('d') == '14') { // Note this is loosely checked!
            $fourteenths[] = $dt->format('Y-m-d');
        }
    }
    
    echo count($fourteenths) . PHP_EOL;
    var_dump($fourteenths);
    

    See it in action here: https://3v4l.org/vPZZ0


    EDIT

    This is probably not an optimal solution as you loop through every day in the date period and check whether it's the fourteenth. Probably easier is to modify the start date up to the next 14th and then check with an interval of P1M.