How I resolved PHP strtotime() of not working with 24-hour time format
I’m making a calendar to show availability. My calendar is “daily,” so I can only show ONE day at a time.
This presents a problem in that if someone is available from 10PM — 2AM. When looping through the times, starting at 10PM, I’ll never reach 2AM (since, as I increment from some block of time starting at 10PM, it’ll stop at 11:59 PM — again, I’m only showing one day).
In this example, the ideal solution was to show:
- 12AM — 2AM — available
- 2AM — 10PM NOT available
- 10PM — 11:59 PM available
To implement, I reversed the open/closed time (available from 2AM — 10PM), but I blocked out all of these times. This gives the sample above. I was displaying 24-hour times, but couldn’t convert it correctly. I tried various date() and strtotime() functions, but I couldn’t add or loop through times correctly.
The problem was that my initial time read “22:00 PM” [ date(“G:i A”, strtotime($OpenTime)); ] … It should have said just “22:00” (no “PM”). By adjusting the original input format (to remove the “A” for AM/PM), I was able to convert the times correctly.
Lesson learned: When you’re adding/manipulating/looping through times in PHP, don’t include AM/PM.
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