PHP - Comparing time
I'm working on a calendar/planner web app and I need to compare the start and end times of events before I store them in my DB. An event can only have a range of one day and between 8am and midnight. The start time always has to take place before the end time.
The post values come from the form in the following format hh:mm:ss
(12:14:00
) etc.. so I can store them in my database without开发者_运维知识库 much hassle. Is there any way I can compare these times?
Thanks a lot!
If those times are in the database, comparison operator of the database would works. For example:
SELECT * FROM table WHERE time < NOW()
In PHP, the easiest way to compare times is to convert them to timestamps, and then to compare timestamps as integers. You can use strtotime to do that conversion.
For example:
$time1 = "08:00:00";
$time2 = "09:00:00";
if (strtotime($time1) > strtotime($time2) ||
strtotime($time1) < strtotime("08:00:00")) {
...
}
If you're running PHP 5.3, you can use the diff() method of DateTime objects to get the difference in between two dates. But it's possible to do with just timestamps too (1 day = 86400 seconds)
精彩评论