Calculating Time Difference in PHP
In PHP, calculating the time difference between two times is straightforward. This is particularly useful when working with attendance records and determining late or very late employees.
Suppose you have a constant reference time, such as 09:00:59, and a variable time obtained from a database table. To find the time difference, you can leverage the strtotime() function.
Here's a working example:
<?php $checkTime = strtotime('09:00:59'); echo 'Check Time : ' . date('H:i:s', $checkTime); echo '<hr>'; $loginTime = strtotime('09:01:00'); $diff = $checkTime - $loginTime; echo 'Login Time : ' . date('H:i:s', $loginTime) . '<br>'; echo ($diff < 0) ? 'Late!' : 'Right time!'; echo '<br>'; echo 'Time diff in sec: ' . abs($diff); echo '<hr>'; $loginTime = strtotime('09:00:59'); $diff = $checkTime - $loginTime; echo 'Login Time : ' . date('H:i:s', $loginTime) . '<br>'; echo ($diff < 0) ? 'Late!' : 'Right time!'; echo '<hr>'; $loginTime = strtotime('09:00:00'); $diff = $checkTime - $loginTime; echo 'Login Time : ' . date('H:i:s', $loginTime) . '<br>'; echo ($diff < 0) ? 'Late!' : 'Right time!'; ?>
This script demonstrates the calculation for different login time scenarios. Login times before the reference time are considered "right time," while those after are marked as "Late!" and the time difference is displayed in seconds.
The above is the detailed content of How to Calculate Time Difference in PHP for Attendance Records?. For more information, please follow other related articles on the PHP Chinese website!