This topic is locked
[SOLVED]

count hours

10/29/2024 2:06:46 PM
PHPRunner General questions
R
Rudy Lambrechts author

Probably a beginner question... I have 2 fields (start time and end time). Is there a way to create an additional field with the number of hours? Thanks

Davor GeciDevClub member 10/29/2024

In ADD PAGE Before record added and EDIT PAGE Before record updated events add this code:

if ($values["start_time"] && $values["end_time"]) {
// Calculate the difference in seconds
$start = strtotime($values["start_time"]);
$end = strtotime($values["end_time"]);
$diffInSeconds = $end - $start;

// Convert the difference to hours
$values["duration_hours"] = round($diffInSeconds / 3600, 2); // rounding to 2 decimal places
} else {
// If either field is not populated, set duration_hours to null or 0
$values["duration_hours"] = null; // or 0, depending on your preference
}

Hope this helps,
Davor

D
DUKE 10/30/2024

You can also edit your SQL Query:

select
Start_Time,
End_Time,
timestampdiff(hour,Start_Time,End_Time) as Hours
from
tmp_times

Add the timestampdiff line at the end of your SQL query

This will create an additional field (in your application) with the difference.

If you want the difference saved in the database itself you can add an actual additional field to the table: Hours

Then, edit page after record updated add the following line.

db::exec("update tmp_times set `Hours` = timestampdiff(hour,Start_Time,End_Time) where Hours is null")

Carpet bombing update - will do the latest one, as well as all that have not been updated.