Foundry ERP Software
Success in the fast-paced world of foundries depends on accuracy, productivity, and economy. Modern production demands are too great for traditional technologies to meet. Foundry ERP software company
Read MoreSign Up Now and Get FREE CTO-level Consultation.
Time-based validation is one of the most common requirements in PHP web development. Whether you're building an appointment booking system, employee attendance software, online meeting scheduler, hospital management system, or event booking platform, you often need to determine whether a particular time falls between two time slots or calculate the difference between two times.
PHP offers several built-in date and time functions that make these tasks simple and accurate. Instead of performing manual calculations, you can use functions like DateTime, DateInterval, and strtotime() to compare times efficiently.
In this guide, you'll learn how to check whether a time lies between two time slots, calculate the time difference, and implement these techniques in real-world PHP applications.
Many web applications rely on time-based conditions. Here are some common examples:
Appointment booking systems
Doctor consultation portals
Online class scheduling
Meeting room reservation systems
Employee attendance management
Restaurant table booking
Event registration platforms
Delivery slot management
Hotel check-in and check-out validation
For example, if a customer wants to book an appointment at 11:30 AM, you need to verify whether it falls between the available slot of 10:00 AM and 12:00 PM.
PHP includes several built-in functions for working with dates and times.
| Function | Purpose |
| strtotime() | Converts a time string into a Unix timestamp |
| DateTime() | Creates a DateTime object |
| DateInterval | Represents the difference between two dates or times |
| date() | Formats date and time |
| time() | Returns the current Unix timestamp |
Among these, DateTime is generally recommended because it is more readable, flexible, and suitable for modern PHP applications.
The simplest way to compare times is by converting them into Unix timestamps.
<?php
$start = strtotime("09:00 AM");
$end = strtotime("06:00 PM");
$current = strtotime("11:30 AM");
if($current >= $start && $current <= $end){
echo "Current time is within the time slot.";
}else{
echo "Current time is outside the time slot.";
}
?>
Current time is within the time slot.
The strtotime() function converts human-readable time into Unix timestamps.
For example:
09:00 AM → Timestamp
11:30 AM → Timestamp
06:00 PM → Timestamp
PHP then compares the numeric values rather than the text, making the comparison accurate and efficient.
The DateTime class provides a cleaner and more object-oriented approach.
<?php
$start = new DateTime('09:00');
$end = new DateTime('18:00');
$current = new DateTime('11:30');
if($current >= $start && $current <= $end){
echo "Time exists between the slots.";
}else{
echo "Time is outside the slot.";
}
?>
Time exists between the slots.
Compared to strtotime(), the DateTime class offers several advantages:
Easier to read and maintain
Supports time zones
Handles date and time together
Simplifies calculations
Suitable for enterprise applications
Because of these benefits, many PHP developers prefer using DateTime in production projects.
Sometimes, you don't just need to check whether a time falls within a range—you also need to calculate the duration between two times.
PHP's diff() method makes this easy.
<?php
$start = new DateTime("09:30");
$end = new DateTime("12:15");
$difference = $start->diff($end);
echo $difference->h." Hours ";
echo $difference->i." Minutes";
?>
2 Hours 45 Minutes
The diff() method returns a DateInterval object, which provides details such as hours, minutes, days, months, and years depending on the values being compared.
Imagine an office allows employees to log in only between 9:00 AM and 6:00 PM.
You can validate login time as follows:
<?php
$officeStart = new DateTime("09:00");
$officeEnd = new DateTime("18:00");
$loginTime = new DateTime("10:45");
if($loginTime >= $officeStart && $loginTime <= $officeEnd){
echo "Login Allowed";
}else{
echo "Office Closed";
}
?>
Login Allowed
This type of validation is commonly used in:
HR Management Systems
Attendance Software
Employee Portals
Payroll Applications
Suppose a clinic accepts appointments only between 10:00 AM and 4:00 PM.
<?php
$slotStart = new DateTime("10:00");
$slotEnd = new DateTime("16:00");
$userTime = new DateTime("03:15 PM");
if($userTime >= $slotStart && $userTime <= $slotEnd){
echo "Appointment Available";
}else{
echo "Please choose another slot.";
}
?>
This validation helps prevent users from selecting unavailable time slots and improves the overall booking experience.
When working with time comparisons in PHP, keep these practices in mind:
Use the DateTime class for modern and maintainable code.
Store time values in a consistent format (preferably 24-hour format).
Set the correct time zone using date_default_timezone_set() to avoid unexpected results.
Validate user input before comparing time values.
Handle edge cases, such as overnight time slots (e.g., 10:00 PM to 6:00 AM), separately.
Instead of writing the same condition again and again, you can create a reusable function.
<?php
function isTimeBetween($startTime, $endTime, $checkTime)
{
$start = new DateTime($startTime);
$end = new DateTime($endTime);
$check = new DateTime($checkTime);
if ($check >= $start && $check <= $end) {
return true;
}
return false;
}
if (isTimeBetween("09:00", "18:00", "14:30")) {
echo "Time is inside the slot.";
} else {
echo "Time is outside the slot.";
}
?>
Time is inside the slot.
This function is useful for booking systems, attendance applications, event schedules, and service availability checking.
Sometimes, you may need the time difference in total minutes instead of hours and minutes.
<?php
$start = strtotime("09:15");
$end = strtotime("11:45");
$differenceInSeconds = $end - $start;
$differenceInMinutes = $differenceInSeconds / 60;
echo "Total Minutes: " . $differenceInMinutes;
?>
Total Minutes: 150
This method is helpful when you need to calculate billing time, consultation duration, parking duration, or employee working minutes.
For user-friendly output, you can display the time difference in hours and minutes.
<?php
$start = new DateTime("08:30");
$end = new DateTime("17:15");
$interval = $start->diff($end);
echo $interval->h . " Hours " . $interval->i . " Minutes";
?>
8 Hours 45 Minutes
This format is easier for users to understand compared to showing only minutes or seconds.
In many applications, you may want to check whether the current server time falls within a particular time range.
<?php
date_default_timezone_set("Asia/Kolkata");
$start = new DateTime("09:00");
$end = new DateTime("18:00");
$current = new DateTime();
if ($current >= $start && $current <= $end) {
echo "Service is currently available.";
} else {
echo "Service is currently unavailable.";
}
?>
This example is useful for:
Customer support availability
Live chat working hours
Food delivery timing
Online consultation timing
Business opening and closing hours
Always set the correct timezone before comparing current time. Otherwise, the result may differ from the actual business location.
A normal time slot starts and ends on the same day, such as 09:00 AM to 06:00 PM. But some businesses work overnight, such as 10:00 PM to 06:00 AM.
In that case, a simple comparison may fail because the end time belongs to the next day.
<?php
function isTimeBetweenOvernight($startTime, $endTime, $checkTime)
{
$start = strtotime($startTime);
$end = strtotime($endTime);
$check = strtotime($checkTime);
if ($start < $end) {
return ($check >= $start && $check <= $end);
} else {
return ($check >= $start || $check <= $end);
}
}
if (isTimeBetweenOvernight("22:00", "06:00", "02:30")) {
echo "Time is within the overnight slot.";
} else {
echo "Time is outside the overnight slot.";
}
?>
Time is within the overnight slot.
This logic is useful for:
Night shift attendance
24/7 support timing
Hotel check-in systems
Hospital emergency services
Late-night food delivery apps
Sometimes, one business may have multiple available time slots. For example, a doctor may be available from 09:00 AM to 12:00 PM and again from 03:00 PM to 06:00 PM.
<?php
$slots = [
["start" => "09:00", "end" => "12:00"],
["start" => "15:00", "end" => "18:00"]
];
$checkTime = "16:30";
$isAvailable = false;
foreach ($slots as $slot) {
$start = new DateTime($slot["start"]);
$end = new DateTime($slot["end"]);
$check = new DateTime($checkTime);
if ($check >= $start && $check <= $end) {
$isAvailable = true;
break;
}
}
if ($isAvailable) {
echo "Selected time is available.";
} else {
echo "Selected time is not available.";
}
?>
Selected time is available.
This method is perfect for appointment booking platforms, coaching class schedules, clinic software, and salon booking systems.
A very important requirement in booking systems is checking whether one time slot overlaps with another.
For example:
Existing slot: 10:00 AM to 11:00 AM
New slot: 10:30 AM to 11:30 AM
These two slots overlap.
<?php
function isSlotOverlapping($start1, $end1, $start2, $end2)
{
$start1 = new DateTime($start1);
$end1 = new DateTime($end1);
$start2 = new DateTime($start2);
$end2 = new DateTime($end2);
return ($start1 < $end2 && $start2 < $end1);
}
if (isSlotOverlapping("10:00", "11:00", "10:30", "11:30")) {
echo "Time slots are overlapping.";
} else {
echo "Time slots are not overlapping.";
}
?>
Time slots are overlapping.
This helps prevent double booking in applications like:
Hotel room booking
Doctor appointment booking
Meeting room reservation
Online class timetable
Event seat booking
Many beginners make small mistakes when comparing time values. Here are some common issues:
if ("9:00" > "12:00") {
echo "Wrong comparison";
}
This is not reliable because PHP may treat the values as strings. Always convert time into timestamps or DateTime objects before comparing.
If your server timezone is different from your business timezone, the current time comparison may be wrong.
Use:
date_default_timezone_set("Asia/Kolkata");
Avoid mixing formats like:
09:00
9 AM
09:00 PM
21:00
Use one standard format throughout the project. The 24-hour format is usually better for database storage and comparison.
A time range like 11:00 PM to 5:00 AM should be handled separately because it crosses midnight.
For clean PHP time comparison, store time in MySQL using the TIME format.
Example:
start_time TIME
end_time TIME
You can store values like:
09:00:00
18:00:00
This makes it easier to compare, filter, and sort time slots in both PHP and SQL.
You can also check time slots directly in MySQL.
SELECT *
FROM appointments
WHERE '10:30:00' BETWEEN start_time AND end_time;
This query returns all records where 10:30:00 falls between the stored start and end time.
However, for complex logic like overnight slots, user-specific time zones, and multiple conditions, PHP handling may be easier and more flexible.
Here are some recommended practices that every PHP developer should follow.
While strtotime() is simple and works well for basic comparisons, the DateTime class offers better readability, flexibility, and support for advanced date and time operations.
Recommended for:
Enterprise applications
Booking systems
CRM software
ERP solutions
Healthcare applications
Always store time values in a consistent format.
Recommended format:
09:00:00
14:30:00
18:45:00
Using the MySQL TIME data type makes comparisons easier and reduces formatting issues.
Different servers may use different default time zones. Always define the correct timezone at the beginning of your application.
<?php
date_default_timezone_set('Asia/Kolkata');
?>
This ensures that all date and time operations produce consistent results.
Never assume that user-entered time values are valid.
For example, validate inputs such as:
Empty values
Invalid formats
Incorrect time ranges
Missing AM/PM values
Proper validation helps avoid unexpected errors and improves application reliability.
Instead of repeating comparison logic throughout your project, create reusable helper functions.
Benefits include:
Cleaner code
Easier maintenance
Reduced duplication
Faster debugging
Better scalability
When processing large datasets, small optimizations can improve performance.
If multiple records use the same start and end time, convert them once instead of repeatedly calling DateTime or strtotime().
Create DateTime objects only when required, especially inside loops processing many records.
For simple conditions, let MySQL handle the filtering before sending results to PHP.
Example:
SELECT *
FROM appointments
WHERE start_time <= '11:00:00'
AND end_time >= '11:00:00';
This reduces the number of records PHP needs to process.
If your application frequently searches by time, indexing the start_time and end_time columns can improve query performance.
Checking time differences between two slots is widely used across industries.
Doctor appointments
Salon bookings
Fitness trainers
Consultants
Shift validation
Login tracking
Working hour calculation
Overtime management
Live class schedules
Student attendance
Exam timing
Webinar management
Check-in validation
Check-out timing
Room availability
Reservation management
Restaurant opening hours
Delivery slot availability
Driver scheduling
Order cut-off timing
Registration windows
Session scheduling
Speaker availability
Venue booking
Many PHP interviews include questions related to date and time handling.
Examples include:
How do you compare two time values in PHP?
What is the difference between strtotime() and DateTime?
How do you calculate the difference between two times?
How do you check if a time falls within a specific range?
How do you handle overnight time slots?
What is the purpose of the diff() method?
How do you calculate total minutes between two times?
Understanding these concepts strengthens both your coding skills and interview preparation.
Comparing time slots is a fundamental requirement in many PHP applications. From appointment scheduling and employee attendance to hotel reservations and online learning platforms, accurate time validation ensures smooth business operations.
PHP provides multiple ways to handle time comparisons, including strtotime(), DateTime, and DateInterval. While strtotime() is suitable for simple tasks, the DateTime class is the preferred choice for modern applications because it is easier to read, supports time zones, and offers powerful methods for comparison and calculation.
By storing time in a standard format, validating user input, handling overnight time ranges, and using reusable helper functions, you can build reliable and scalable PHP applications with confidence.
You can compare DateTime objects or Unix timestamps using conditional operators. If the selected time is greater than or equal to the start time and less than or equal to the end time, it falls within the time slot.
DateTime is recommended for modern PHP applications because it is object-oriented, easier to maintain, supports time zones, and provides advanced methods for date and time calculations.
Use the diff() method of the DateTime class to get a DateInterval object containing hours, minutes, days, and other time components.
Yes. PHP can compare time-only values using either DateTime objects or strtotime(). If no date is provided, PHP uses the current date internally.
When the start time is later than the end time (for example, 10:00 PM to 6:00 AM), use custom comparison logic that accounts for the time range crossing midnight.
Convert both times to Unix timestamps using strtotime(), subtract the values, and divide the result by 60 to get the total number of minutes.
Use the TIME data type and store values in 24-hour format, such as 09:00:00 or 18:30:00. This format is ideal for comparisons and sorting.
Setting the correct timezone ensures accurate date and time calculations, especially for applications serving users in specific regions or multiple countries.
Yes. Store multiple time ranges in an array or database, loop through each slot, and compare the selected time against every available range.
Time slot comparison is widely used in appointment booking systems, hospital management software, employee attendance systems, hotel reservation platforms, event management applications, online learning portals, and food delivery services.
Request a FREE Business Plan.
+91 ▼ Success in the fast-paced world of foundries depends on accuracy, productivity, and economy. Modern production demands are too great for traditional technologies to meet. Foundry ERP software company
Read More
Planning an event today is no longer just about booking a venue and sending invitations. From registrations and marketing to live check-ins and post-event analytics, modern events demand speed, accura
Read More
Technology is becoming a driving factor in the rapidly changing travel and tourism industry, changing how travel firms function. Flight reservation software is among the most important developments in
Read More