0

I'm working on a record keeping system for animals and I have to work out the number of days that the carer looks after one or more animals in any given year.

Sometimes the date rolls over into the next year and I have to work out the number of days spent caring for them in year 1 and also the number of days in year two.

I have put together some code that works except that it won't take the start date as day 1, its ignored.

<?php
date_default_timezone_set('Australia/Sydney');
$start_date = new DateTime('2020-01-01');
$end_date = new DateTime('2021-01-01');
$index = 0;
$period = new DatePeriod($start_date, new DateInterval('P1D'), $end_date);
$oldYear = $start_date->format('Y');
$name = 'Komala';
$lastYear = 0;

echo '<table style="border-style: solid">';
    echo '<tr><td colspan="2">The number of days spent looking after '.$name.'</td>';
        foreach($period as $key=>$date) {
            $yearCheck = $date->format('Y');
            if ($yearCheck === $oldYear){
                echo '';
            }else{
                $lastYear = $index;
                echo '<td colspan="2">';
                echo 'in '. $oldYear .' is: ' . ($lastYear);
                echo '</td>';
            }
            $index++;
            $oldYear = $yearCheck;
        }
        echo '<td>';
            echo 'in '. $oldYear .' is: ' . ($index - $lastYear);
        echo '</td><td>';
            echo 'For a total of '. $index .' days.';
    echo '</td></tr>;';
echo '</table>';
?>

When I use the date range as above from 01 Jan 2020 to 02 Jan 2021 it should say 368 days but instead it says 367.

Code output

I tried to use DatePeriod:: to try to include the start date but I can't seem to make it work.

Can someone help please?

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Your problem is that `DatePeriod` doesn't include the end date, so you need to add one day to it to get an inclusive list e.g. `$end_date = new DateTime('2021-01-02 + 1 day');`. See the comments on the duplicate – Nick Feb 07 '20 at 04:45
  • Thanks Nick, sorry I didn't that up in my search for some reason. – Rod-Miller Feb 07 '20 at 04:59
  • No worries - it's not really well documented in the manual and hard to find on SO too. – Nick Feb 07 '20 at 05:16

0 Answers0