How I resolved the PHP error of calculating the difference between two dates

I was trying to calculate the difference between two dates, December 1, 2020 and December 2, 2021. I needed the dates to be formatted, so my code was something like this:

date("D, M jS, g:i A", myDateHere )

This resulted in:

Start Date: Tue, Dec 1st, 7:00 AM

End Date: Thu, Dec 2nd, 7:30 AM

The problem was that I was incorrectly calculating the dates to be only 3 days apart instead of 1 year. The error was because I didn’t include the year in the date format.

The solution: I should have calculated the difference in the dates with the full date including the year, before formatting it. When I calculated the formatted date, it subtracted Thursday from Tuesday (resulting in 3 days), despite it being a year apart.

The lesson learned: don’t calculate dates that have been formatted. Compare the “raw” dates and then print out the final date in the desired format.

Like this style of writing? 👍👍 Interested in creating a PHP web application and already know what a “variable” is and the concept of an “if” statement? Check out my book: Web Development for Intermediate Programmers — with PHP