Reputation: 1625
I'm trying to calculate the difference in minutes between two database fields using php. the first field (attendance) is timestamp, and the second field (check_in) is time.
this is the PHP code I tried:
$sql = "
select e.attendance, s.check_in, s.check_out
from employee e
inner join my_schedule s on s.id = e.sch_id
where e.emp_id = '".$emp_id."'
";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_array($query);
echo 'employee checked in at '.strtotime($row['attendance']); // employee checked in at 2015-11-18 08:48:23
$late = round((strtotime($row['check_in']) - strtotime($row['attendance']))/60,0);
if ($late < 0) {
echo "you're late!!";
}
the "you're late" message did appear but there's also an error message :
strtotime() [function.strtotime]: Called with an empty time parameter. in C:\Program Files\xampp\htdocs\myproject\page1.php
why do the error only appear when I store the value from strtotime() into a variable?
I'm using :
Current PHP version: 5.0.5
MySQL 4.1.14
UPDATE:
this is the result of echo var_dump($row['attendance']);
(data type timestamp
)
string(19) "2015-11-18 08:48:23"
and this is echo var_dump($row['check_in']);
(data type time
)
string(8) "08:00:00"
is it normal that PHP perceives those fields as string instead of time?
UPDATE 2 : I found the source of the problem! the query used a parameter (emp_id) and one of the emp_id returns a zero result so the strtotime returned the error.
the solution is that I added an IF
clause to make sure that the rows have a valid value before running strtotime.
if ($row['check_in'] != '' && $row['attendance'] != '') {
$late = round((strtotime($row['check_in']) - strtotime($row['attendance']))/60,0);
}
Upvotes: 1
Views: 1049
Reputation: 4038
The issue here is that strtotime expects a date, not just a time. So you can extract the date from your attendance like this:
$attendance = "2015-11-18 08:48:23";
$check_in = "08:00:00";
if ( strlen($check_in) <= 8 ) { // Does not include date. Prepend it automatically:
$parts = explode(" ",$attendance);
$attendance_date = $parts[0];
$check_in = "{$attendance_date} {$check_in}";
}
$late = round((strtotime($check_in) - strtotime($attendance))/60,0);
Just to be clear before we run our calculations we want to end up with:
$attendance = "2015-11-18 08:48:23";
$check_in = "2015-11-18 08:00:00";
Here are some more examples of strtotime()
echo strtotime("2015-11-18 08:48:23"),"\n";
echo strtotime("18 November 2015"),"\n";
echo strtotime("now"),"\n";
echo strtotime("+1 day"),"\n";
echo strtotime("+1 week"),"\n";
echo strtotime("+1 week 2 days 3 hours 4 seconds"),"\n";
echo strtotime("last Monday"),"\n";
echo strtotime("next Friday"),"\n";
Read more: php.net/strtotime
Upvotes: 2
Reputation: 2372
if this is comes in form of warning then put @ before the strtotime().
$late = @strtotime($row['check_in']) - @strtotime($row['attendance']);
its just hide warnings.
Upvotes: -1