Comparing times and dates in php
Writing this up to help remind me of the best way to do this for future…
I recently created a plugin that allowed admin to create alerts/notices that can then be displayed via a modal on any page where a shortcode was added. I did this because I was getting a lot of request for Covid-19 alerts last April. When creating it, I used a cookie so that I could use a “$hasSeen” variable and if someone was to close out the modal, it set a cookie so that if they navigated around, they didn’t get hit over and over with the alert.
I also built it to display for a specified date range. All worked great until we got into October. To be completely honest, I never really thought it would be in use this long and I didn’t take in account how date are compared when the start date is 04/10/20 and when you get into October, it becomes 10/10/20…
For starters, I was comparing strings vs. unix timestamp, so I went down the strtotime() route and was still having difficulties and then I found the DateTime class. Ie.
$startDate = new DateTime($startValue);
$endDate = new DateTime($endValue);
$today = new DateTime();
I was then able to do something like the following:
if (($today >= $startDate) && ($today <= $endDate)) {
// display the alert…
}
This new DateTime class completely solved my issue and I didn’t need to worry about timezones…