Sunday 8 August 2021

Spot The Bug: Twenty-twenty

Today's Spot The Bug session is about reports; specifically, report dates. We'll be going through some good old-fashioned PHP and examining a very common pitfall.

Let's get started,
bug-hunters!

There was a case last year in November where I had to supply an inventory report, containing an opening balance at a certain date, right in the header. As the bug revolves mostly around the header, I won't reproduce the entire code base here.
<body>
    <?php
        $reportDate = date("j M yy");
        $opening = date("1 M yy");
        $closing = date("1 M yy", strtotime($opening . " +1 months -1 days"));
    ?>

    <h1>Inventory Report</h1>
    <p>Report Generated On <?php echo $reportDate; ?></p>
    <hr />
    <table>
        <tr>
            <td width="50%" valign="top">
                Opening balance as at <?php echo $opening; ?>
            </td>

            <td width="50%" valign="top">
                <table>
                    <tr>
                        <td width="30%">
                            <b>Attn:</b>
                        </td>

                        <td width="70%">
                             Agnes Ng
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <b>Contact:</b>
                        </td>

                        <td>
                             11225566
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <b>Designation:</b>
                        </td>

                        <td>
                             Account Manager
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>


This was what it produced, which looked correct.


What went wrong

However, at the end of January, users alerted me to an anomaly in the report. This was freaky. An opening balance set at a hundred years from now?!


Why it went wrong

This was an issue with the date format I had used - most notably, the year. My intention had been to use a four-digit year, but I had been using "yy". "y" produces "20" if the current year is 2020. So "yy" naturally produced "2020".

However, in 2021, it would produce 2121!


How I fixed it

All I needed to do was this.
<?php
    $reportDate = date("j M Y");
    $opening = date("1 M Y");
    $closing = date("1 M Y", strtotime($opening . " +1 months -1 days"));
?>


And there it was!


Moral of the story

All this could have been avoided if I had tested more robustly - instead of just testing a month ahead, it would have been better to test a couple years into the future. Normally, the most insidious bugs don't show up as a compilation error, or even right away. Today's example was one such bug.

I guess hindsight is always 20-20!
T___T

No comments:

Post a Comment