Skip to content
Advertisement

Finding Average Time for Created At and Updated At – PHP & MYSQL

I have a table to which has created_at and updated_at. Created at is when the client purchased the order and the updated_at field is updated when the order is approved like below.

I want to get the average time it took my admin to approve the items in the table below. This is my sql

SELECT AVG( TIMEDIFF(  `created_at` ,  `updated_at` ) ) AS time_average
FROM table

My results is 8025356.2742000870. Am I on the right path and how do I convert the average time to hours like 2hrs 15mins

Table

Item        created_at                   updated_at

Iphone     2020-01-01 00::00::00         2020-02-04 10::20::20

Samsung    2020-04-01 08::40::00         2020-03-03 10::20::20

Advertisement

Answer

Yes, you can find the answer with using strtotime() $time = date('H :i', strtotime($res)); This is what I have tried,

$connect = new mysqli($localhost, $username, $password, $dbname);

$sql = "SELECT AVG( TIMEDIFF(  `created_at` ,  `updated_at` ) ) AS time_average FROM table";
$result = $connect->query($sql);
$row  = $result->fetch_assoc();
$res = $row["time_average"];
//echo "avg".$res."<br/>";

$time = date('H :i', strtotime($res));
echo "time avarage : ".$time;

Then you can use explode method to discribe as follow,

$timeArray =explode(":", $time);
echo $timeArray[0]."hrs ".$timeArray[1]."mins"; 

It’s work fine, and think It will help you.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement